O'Reilly logo

iOS 8 SDK Development, 2nd Edition by Janie Clayton, Chris Adamson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Optionals

To see what the problem is when we fetch a dictionary member by name, let’s imagine if we added the following line:

 
var​ mass = planetaryMass[​"Gallifrey"​]

Considering that “Gallifrey” is a fictional planet (and was, for a time, erased from history even within that fiction), it’s not in our dictionary, so there’s no valid answer here. So what value should be returned for a value that doesn’t exist? Double is a numeric type, not an object, so we can’t just have it be nil as a means of saying “no object.” Can it be 0? No, 0 is a perfectly good value for a floating-point number. So what do we do here?

Swift uses a concept called optionals which encapsulate both knowing whether or not there is a value, and if so, what the value is. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required