MΓ³dulo 02 Β· Swift, One Level Deeper β LecciΓ³n 1 de 5 Β· ~17 min
Optionals: When a Value Might Not Exist
Sometimes there's just no value
Every pet in PawWalk has a name. But its age? A rescue dog's age is often a guess the owner never enters. And not every walker uploads a profile photo. Swift forces you to be honest about missing data: a value that might not be there gets a different type.
Double is always a number. Double? β read it as "optional Double" β is either a number or nil, Swift's word for "nothing here." In the real models file, Pet.ageYears is a Double? and Walker.photoURL is a String? for exactly these reasons.
The
?is part of the type.StringandString?are different types, and Swift will not let you use aString?as if the value were definitely there. That one rule eliminates the #1 crash in most other languages: using a value that doesn't exist.