Optionals

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Open the Lesson01-Review-Basics playground. Start on the Lesson01-optionals page.

Failable Initializers

Some Swift standard types have initializers that can fail, so their return type is an optional. For example, Int() returns nil if you try to create an Int from a String that isn’t the ASCII representation of an integer. Run these two lines of code:

let value = Int("3")  // 3
let failedValue = Int("nope")  // nil
enum PetFood: String {
  case kibble, canned
}

let morning = PetFood(rawValue: "kibble")  // .kibble
let snack = PetFood(rawValue: "fuuud!")  // nil
init?(squareFeetAsString: String) {  // 1
  guard let squareFeet = Int(squareFeetAsString) else {  // 2
    return nil
  }
  self.squareFeet = squareFeet
}
let house = PetHouse(squareFeetAsString: "100")  // PetHouse?
let nopeHouse = PetHouse(squareFeetAsString: "nope")  // nil

Optional Chaining

Many people own pets — but not all. Some pets have a favorite toy, and others don’t. Some of these toys make noise, and others don’t. Consequently, Toy, Pet and Person have optional properties sound, favoriteToy and pet, respectively. Run the following code to create three Person objects:

let janie = Person(pet: Pet(name: "Delia", kind: .dog, favoriteToy: Toy(kind: .ball, color: "Purple", sound: .bell)))
let tammy = Person(pet: Pet(name: "Evil Cat Overlord", kind: .cat, favoriteToy: Toy(kind: .mouse, color: "Orange")))
let felipe = Person()
Person objects
Leqhev onretqj

if let sound = janie.pet?.favoriteToy?.sound {
  print("Sound \(sound).")
} else {
  print("No sound.")
}

if let sound = tammy.pet?.favoriteToy?.sound {
  print("Sound \(sound).")
} else {
  print("No sound.")
}

if let sound = felipe.pet?.favoriteToy?.sound {
  print("Sound \(sound).")
} else {
  print("No sound.")
}
Sound of favorite toy of pet
Jeamn en gihoqadu xow ag zer

See forum comments
Download course materials from Github
Previous: Introduction Next: Throw-Catch