SlideShare a Scribd company logo
1 of 21
Download to read offline
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.

More Related Content

More from 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
 

More from 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
 

Recently uploaded

Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024Janet Corral
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 

Recently uploaded (20)

Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 

Optionals

  • 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.