Book Image

Mastering Swift

By : Jon Hoffman
Book Image

Mastering Swift

By: Jon Hoffman

Overview of this book

Table of Contents (22 chapters)
Mastering Swift
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

The need for optional types in Swift


Now, the burning question is why does Swift need optionals? To understand why Swift has optionals, 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 the following lines of code are valid:

int i;
MyObject *m;

Now, let's say that the MyObject class 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 might be that this code would display Value: 10; however, this would be wrong. In reality, this code would display Value: 0 because we did not initialize the m object prior to using it.

When we forget to initialize an object or set a value for a variable, we can get...