Optionals in Swift explained – with a cat in a box!

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:

ch2_08_cat1.png

Inside the box you know you have one of two things – either no cat…

ch2_08_cat3_open.png

…or a cat!

ch2_08_cat4_open.png

What you have just imagined, is a Cat optional!

ch2_08_cat2.png

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:

Unknown's avatar

iOS development with Swift - book: https://manning.com/books/ios-development-with-swift video course: https://www.manning.com/livevideo/ios-development-with-swift-lv

Tagged with:
Posted in Swift

Leave a comment