If you’ve come to Swift from a language that doesn’t use optionals, you might find the concept a little strange and the syntax unfamiliar at first. Sometimes it helps to learn the unfamiliar with something familiar – in my lightning tour of optionals, I explain optionals with a cat in a box!
So – imagine you have a box:
Inside the box you know you have one of two things – either no cat…
…or a cat!
What you have just imagined, is a Cat optional!
As you can see, you declare an optional with the data type of its contents (Cat
in this example), followed by a question mark:
var cat:Cat?
But now that we have a Cat
optional, how do we get at its contents – or put another way – how do we unwrap the box?
Check my lightning tour of Optionals to find out:
Leave a Reply