SlideShare ist ein Scribd-Unternehmen logo
1 von 21
Downloaden Sie, um offline zu lesen
Unit 3—Lesson 1:
Optionals
nil
struct Book {
let name: String
let publicationYear: Int
}
let firstHarryPotter = Book(name: "Harry Potter and the Sorcerer's Stone", 

publicationYear: 1997)
let secondHarryPotter = Book(name: "Harry Potter and the Chamber of Secrets", 

publicationYear: 1998)
let books = [firstHarryPotter, secondHarryPotter]
nil
let unannouncedBook = Book(name: "Rebels and Lions",
publicationYear: ???)
nil
let unannouncedBook = Book(name: "Rebels and Lions",
publicationYear: 0)
nil
let unannouncedBook = Book(name: "Rebels and Lions",
publicationYear: 2017)
nil
let unannouncedBook = Book(name: "Rebels and Lions",
publicationYear: nil) Nil is not compatible with expected argument type ‘Int’!
struct Book {
let name: String
let publicationYear: Int?
}
let firstHarryPotter = Book(name: "Harry Potter and the Sorcerer's Stone",
publicationYear: 1997)
let secondHarryPotter = Book(name: "Harry Potter and the Chamber of Secrets", 

publicationYear: 1998)
let books = [firstHarryPotter, secondHarryPotter]
let unannouncedBook = Book(name: "Rebels and Lions", publicationYear: nil)
Specifying the type of an optional
var serverResponseCode: Int? = 404



var serverResponseCode: Int? = nil
‘nil’ requires a contextual type!
var serverResponseCode = 404
var serverResponseCode = nil
Force-unwrap
Working with optional values
if publicationYear != nil {
let actualYear = publicationYear!
print(actualYear)
}
let unwrappedYear = publicationYear! error: Execution was interrupted!
Optional binding
Working with optional values
if let constantName = someOptional {
//constantName has been safely unwrapped for use within the braces.
}
if let unwrappedPublicationYear = book.publicationYear {
print("The book was published in (unwrappedPublicationYear)")
}
else {
print("The book does not have an official publication date.")
}
Return values
Functions and optionals
let string = "123"
let possibleNumber = Int(string)
let string = "Cynthia"
let possibleNumber = Int(string)
Defining
Functions and optionals
func printFullName(firstName: String, middleName: String?, lastName: String)
func textFromURL(url: URL) -> String?
Failable initializers
struct Toddler {
var birthName: String
var monthsOld: Int
}
Failable initializers
struct Toddler {
var birthName: String
var monthsOld: Int
init?(birthName: String, monthsOld: Int) {
if monthsOld < 12 || monthsOld > 36 {
return nil
} else {
self.birthName = birthName
self.monthsOld = monthsOld
}
}
}
Failable initializers
let possibleToddler = Toddler(birthName: "Joanna", monthsOld: 14)
if let toddler = possibleToddler {
print("(toddler.birthName) is (toddler.monthsOld) months old")
} else {
print("The age you specified for the toddler is not between 1 and 3 yrs of age")
}
Optional chaining
class Person {
var age: Int
var residence: Residence?
}
class Residence {
var address: Address?
}
class Address {
var buildingNumber: String?
var streetName: String?
var apartmentNumber: String?
}
Optional chaining
if let theResidence = person.residence {
if let theAddress = theResidence.address {
if let theApartmentNumber = theAddress.apartmentNumber {
print("He/she lives in apartment number (theApartmentNumber).")
}
}
}
Optional chaining
if let theApartmentNumber = person.residence?.address?.apartmentNumber {
print("He/she lives in apartment number (theApartmentNumber).")
}
Implicitly Unwrapped Optionals
class ViewController: UIViewController {
@IBOutlet weak var label: UILabel!
}
Unwraps automatically

Should only be used when need to initialize an object without supplying the value
and you’ll be giving the object a value soon afterwards
Lab: Optionals.playground
Unit 3, Lesson 1
Open and complete the exercises in Lab - Optionals.playground
© 2017 Apple Inc. 

This work is licensed by Apple Inc. under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International license.

Weitere ähnliche Inhalte

Mehr von SV.CO

Segues and navigation controllers
Segues and navigation controllersSegues and navigation controllers
Segues and navigation controllersSV.CO
 
Camera And Email
Camera And EmailCamera And Email
Camera And EmailSV.CO
 
Scroll views
Scroll viewsScroll views
Scroll viewsSV.CO
 
Intermediate table views
Intermediate table viewsIntermediate table views
Intermediate table viewsSV.CO
 
Table views
Table viewsTable views
Table viewsSV.CO
 
Closures
ClosuresClosures
ClosuresSV.CO
 
Protocols
ProtocolsProtocols
ProtocolsSV.CO
 
App anatomy and life cycle
App anatomy and life cycleApp anatomy and life cycle
App anatomy and life cycleSV.CO
 
Extensions
ExtensionsExtensions
ExtensionsSV.CO
 
Gestures
GesturesGestures
GesturesSV.CO
 
View controller life cycle
View controller life cycleView controller life cycle
View controller life cycleSV.CO
 
Controls in action
Controls in actionControls in action
Controls in actionSV.CO
 
Auto layout and stack views
Auto layout and stack viewsAuto layout and stack views
Auto layout and stack viewsSV.CO
 
Custom view
Custom viewCustom view
Custom viewSV.CO
 
Tab bar controllers
Tab bar controllersTab bar controllers
Tab bar controllersSV.CO
 
Displaying data
Displaying dataDisplaying data
Displaying dataSV.CO
 
Loops
LoopsLoops
LoopsSV.CO
 
Enumerations
EnumerationsEnumerations
EnumerationsSV.CO
 
Collections
CollectionsCollections
CollectionsSV.CO
 
Scope
ScopeScope
ScopeSV.CO
 

Mehr von SV.CO (20)

Segues and navigation controllers
Segues and navigation controllersSegues and navigation controllers
Segues and navigation controllers
 
Camera And Email
Camera And EmailCamera And Email
Camera And Email
 
Scroll views
Scroll viewsScroll views
Scroll views
 
Intermediate table views
Intermediate table viewsIntermediate table views
Intermediate table views
 
Table views
Table viewsTable views
Table views
 
Closures
ClosuresClosures
Closures
 
Protocols
ProtocolsProtocols
Protocols
 
App anatomy and life cycle
App anatomy and life cycleApp anatomy and life cycle
App anatomy and life cycle
 
Extensions
ExtensionsExtensions
Extensions
 
Gestures
GesturesGestures
Gestures
 
View controller life cycle
View controller life cycleView controller life cycle
View controller life cycle
 
Controls in action
Controls in actionControls in action
Controls in action
 
Auto layout and stack views
Auto layout and stack viewsAuto layout and stack views
Auto layout and stack views
 
Custom view
Custom viewCustom view
Custom view
 
Tab bar controllers
Tab bar controllersTab bar controllers
Tab bar controllers
 
Displaying data
Displaying dataDisplaying data
Displaying data
 
Loops
LoopsLoops
Loops
 
Enumerations
EnumerationsEnumerations
Enumerations
 
Collections
CollectionsCollections
Collections
 
Scope
ScopeScope
Scope
 

Kürzlich hochgeladen

ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 

Kürzlich hochgeladen (20)

ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 

Swift Optionals Unit 3 Lesson 1

  • 2. nil struct Book { let name: String let publicationYear: Int } let firstHarryPotter = Book(name: "Harry Potter and the Sorcerer's Stone", 
 publicationYear: 1997) let secondHarryPotter = Book(name: "Harry Potter and the Chamber of Secrets", 
 publicationYear: 1998) let books = [firstHarryPotter, secondHarryPotter]
  • 3. nil let unannouncedBook = Book(name: "Rebels and Lions", publicationYear: ???)
  • 4. nil let unannouncedBook = Book(name: "Rebels and Lions", publicationYear: 0)
  • 5. nil let unannouncedBook = Book(name: "Rebels and Lions", publicationYear: 2017)
  • 6. nil let unannouncedBook = Book(name: "Rebels and Lions", publicationYear: nil) Nil is not compatible with expected argument type ‘Int’!
  • 7. struct Book { let name: String let publicationYear: Int? } let firstHarryPotter = Book(name: "Harry Potter and the Sorcerer's Stone", publicationYear: 1997) let secondHarryPotter = Book(name: "Harry Potter and the Chamber of Secrets", 
 publicationYear: 1998) let books = [firstHarryPotter, secondHarryPotter] let unannouncedBook = Book(name: "Rebels and Lions", publicationYear: nil)
  • 8. Specifying the type of an optional var serverResponseCode: Int? = 404
 
 var serverResponseCode: Int? = nil ‘nil’ requires a contextual type! var serverResponseCode = 404 var serverResponseCode = nil
  • 9. Force-unwrap Working with optional values if publicationYear != nil { let actualYear = publicationYear! print(actualYear) } let unwrappedYear = publicationYear! error: Execution was interrupted!
  • 10. Optional binding Working with optional values if let constantName = someOptional { //constantName has been safely unwrapped for use within the braces. } if let unwrappedPublicationYear = book.publicationYear { print("The book was published in (unwrappedPublicationYear)") } else { print("The book does not have an official publication date.") }
  • 11. Return values Functions and optionals let string = "123" let possibleNumber = Int(string) let string = "Cynthia" let possibleNumber = Int(string)
  • 12. Defining Functions and optionals func printFullName(firstName: String, middleName: String?, lastName: String) func textFromURL(url: URL) -> String?
  • 13. Failable initializers struct Toddler { var birthName: String var monthsOld: Int }
  • 14. Failable initializers struct Toddler { var birthName: String var monthsOld: Int init?(birthName: String, monthsOld: Int) { if monthsOld < 12 || monthsOld > 36 { return nil } else { self.birthName = birthName self.monthsOld = monthsOld } } }
  • 15. Failable initializers let possibleToddler = Toddler(birthName: "Joanna", monthsOld: 14) if let toddler = possibleToddler { print("(toddler.birthName) is (toddler.monthsOld) months old") } else { print("The age you specified for the toddler is not between 1 and 3 yrs of age") }
  • 16. Optional chaining class Person { var age: Int var residence: Residence? } class Residence { var address: Address? } class Address { var buildingNumber: String? var streetName: String? var apartmentNumber: String? }
  • 17. Optional chaining if let theResidence = person.residence { if let theAddress = theResidence.address { if let theApartmentNumber = theAddress.apartmentNumber { print("He/she lives in apartment number (theApartmentNumber).") } } }
  • 18. Optional chaining if let theApartmentNumber = person.residence?.address?.apartmentNumber { print("He/she lives in apartment number (theApartmentNumber).") }
  • 19. Implicitly Unwrapped Optionals class ViewController: UIViewController { @IBOutlet weak var label: UILabel! } Unwraps automatically Should only be used when need to initialize an object without supplying the value and you’ll be giving the object a value soon afterwards
  • 20. Lab: Optionals.playground Unit 3, Lesson 1 Open and complete the exercises in Lab - Optionals.playground
  • 21. © 2017 Apple Inc. This work is licensed by Apple Inc. under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International license.