O'Reilly logo

Mastering Swift 4 - Fourth Edition by Jon Hoffman

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

The need for optional types in Swift

Now, the burning question is, Why does Swift need optionals? To understand this question, we should examine what problems optionals are designed to solve.

In most languages, it is possible to create a variable without giving it an initialized value. For example, in Objective-C, both of these lines of code are valid:

int i; 
MyObject *m; 

Now, let's say that the MyObject class, written in Objective-C, has the following method:

-(int)myMethodWithValue:(int)i { 
  return i*2; 
} 

This method takes the value passed in from the i parameter, multiplies it by 2, and returns the results. Let's try to call this method using the following code:

MyObject *m; 
NSLog(@"Value: %d",[m myMethodWithValue:5]); 

Our first thought ...

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