Optional types

In our day-to-day application development, we encounter situations where we expect to receive a value but we do not receive it. For instance, suppose that we have a list of items and we need to search for a particular value in the list. The particular value that we are looking for might not be on the list. Other examples can be calling a web service and receiving a JSON payload without the fields that we are looking for, or querying a database and not receiving the expected values.

What are we going to receive when the value is not there, and how will we handle this absence?

In programming languages such as C, it is possible to create a variable without giving it a value. If we try to use the variable before assigning a value, we would get an undefined value.

In Swift, we can define a variable without giving it a value, but we cannot use it without assigning some value to it. In other words, we need to initialize it before being able to use it. This feature of Swift ensures that we will not receive undefined values.

What about the scenarios where we need to define a variable and we do not know what the value is going to be?

To overcome these kinds of scenario, Swift provides optional types that can have some or none values and can be used in situations where a value may be absent.

A question mark (?) is used to define a variable as optional. The following example presents an example of optional definition:

// Optional value either contains a value or contains nil 
var optionalString: String? = "A String literal"
optionalString = nil

In this example, we have defined a variable that is of an optional type. The String? type is an optional type that may wrap a String value in it.

We were able to assign nil to optionalString. If we try to assign nil to any non-optional type in Swift, the compiler will complain about it, unlike some other languages such as Objective-C.

For instance, in the following example, the compiler will complain that Nil cannot be assigned to type 'String':

The compile time checking of non-existent values in Swift to prevent runtime errors is one of the features of type safety in Swift. Type safety makes it easier to catch problems in the earlier stages of development. Let's examine an example in Objective-C to see the real value of Optionals:

NSString *searchedItem = [self searchItem: @"an item"]; 
NSString *text = @"Found item: ";
NSString *message = [text stringByAppendingString: searchedItem];

Suppose that we have a list for which we initiate a search by calling searchItem. In this case, our searchItem method takes NSString and returns NSString. The result of this call can be nil. If we use the returned NSString and try to append it to another NSString, it will compile but may crash the application if searchItem is nil.

We could remedy this problem by checking whether searchedItem is not nil before using it. However, there might be some cases where other developers forgot to do it or did not see the necessity of it.

For sure, it is safer to receive compile time complaints about these kinds of usage. As Swift is type-safe, we will not encounter any such surprises during runtime.

So, we have understood why we need an optional type, but what is it and how is it defined? Under the hood, Optional is an enum with two cases in it--one is none and the other one is some with its associated generic value, as follows:

enum Optional<T> { 
case None
case Some(T)
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset