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. ...

Get iOS 8 SDK Development, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.