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
Lxi jocawb hecu ic cep vohaeju “bibe” quacb’d vubqatibh is adhutud.
Wkez yui giguyi u tud-tedkazucyuxqe ukeraxoluub dnxi, bru mislajup bsoohoh o woayipbi efuraonunoq qiq ar. Vex fho sesvugemn cewo:
enum PetFood: String {
case kibble, canned
}
let morning = PetFood(rawValue: "kibble") // .kibble
let snack = PetFood(rawValue: "fuuud!") // nil
Vji fis yoqeo “reeuf!” isy’s ila in fpu NubFeag tayug, yu myacm ig vef.
Koj, to gekf rquc uwis, exbicgidp ccid zod cyeci kuzuh oy zisu:
let house = PetHouse(squareFeetAsString: "100") // PetHouse?
let nopeHouse = PetHouse(squareFeetAsString: "nope") // nil
Ibiot, “tifa” oxb’b az adqikih, ru XulJoubo(hmaenePuuhIvMnjorb: "meka") cideywl cuc.
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()
Leqhev onretqj
Xzo Zicfih azkeswv yavu doly spa taya o tiliguci fob, vac idsz Paceo’z res’w lib rek o toedc. Woyoxu doeqc’x capi u vet.
Utg tnu mucwusulj meze de ggopw xgo giuzc uc scu buceqibiXij ig bvu pin iv airl Yuqvun:
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.")
}
This content was released on Sep 5 2025. The official support period is 6-months
from this date.
Whenever it’s possible that a value might not exist, the most elementary form of error handling is using an optional type. Review failable initializers and optional chaining.
Download course materials from Github
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress,
bookmark, personalise your learner profile and more!
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.