English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Swift Optional Types (Optional)

In this article, you will learn about optionals, their use cases, and optional handling in Swift.

In the previous article, we learned about the different data types available in Swift, and also noticed that the variables or constants declared with these types contain default values.

Example:

let someValue = Int()
print(someValue)

When the program is run, the output is:

0

However, there is another data type called Optional in Swift, which has a default value of nil. If you want a variable or constant to not contain any value, you can use Optional. Optional types can contain a value or not contain a value (nil).

Technically, you can think of it as an optional shoe box. The shoe box may contain shoes or may not. Therefore, when taking out the shoes from the box, you should know in advance.

How to declare an optional?

You can simply represent the data type as Optional by appending. The method is to append ! or ? to the type. If the optional variable contains a value, it returns the value as Optional <Value>, otherwise it returns nil.

Example1: How to declare an optional?

var someValue: Int?
var someAnotherValue: Int! =
print(someValue)
print(someAnotherValue)

When the program is run, the output is:

nil
nil

In the above program, we initialized an optional type using ? and !. Both methods can create optional methods, but there is a major difference that we will discuss below.

Declaring an optional Int means that the variable will have an integer value or no value. Since no value is assigned to the variable, you can see two print statements output nil on the screen.

Example2: Assigning and accessing values from an optional object

let someValue: Int? = 5
print(someValue)
print(someValue!)

When the program is run, the output is:

Optional(5)
5

In the above program, we declared an optional Int type and assigned a value to it5.

Printing an optional as print(someValue) will not return5, but instead of Optional (5) has the form as described above: Optional <Value>. To access <Value> from it, we need a method called unwrapping (unwrapping) mechanism.

You can unpack through the mechanism in the variable/Appending the character ! at the end of a constant to expand the optional content, as shown in the following line: print(someValue!). print(someValue!) unpacks the optional content and outputs it on the screen. 5.

But remember, this unwrapping mechanism should only be used when you are sure that the optional option has a value when accessed.

Example3: Explicitly declare an unwrapped optional

You can also create unwrapped optional content in the following way:

let someValue: Int! = 5
print(someValue)

When the program is run, the output is:

5

In the above program, Int! creates an unwrapped optional content, which automatically unpacks the value when you access it, so you don't have to use the ! character every time.

Make sure that the variable always has a value when accessing these optional options. If not, it will lead to a fatal error crash.

Example4: Fatal error occurs when accessing a null unwrapped optional object

var someValue: Int!
var unwrappedValue: Int = someValue //crashes due to this line

When you run this program, you will get a fatal error crash: unexpected nil encountered while unwrapping Optional value, because the code unwrappedValue: Int = someValue tries to assign the value from Optional someValue to the variable unwrappedValue.

However, somevalue is an optional type that contains a nil value. Attempting to assign a nil value to the variable unwrappedValue (which is not an Optional) will cause a crash.

The following will explain different methods to handle this situation.

Optional handling

To use optional values, you need to unwrap them. A better way to use optional values is through conditional unwrapping, rather than using the ! operator to force unwrapping.

This is because conditional unwrapping asksIs it necessary to check if this variable has a value?.If so, provide the value; otherwise, handle the nil case.

On the contrary, forced unwrapping indicates that the variable indeed has a value when it is used. Therefore, when you force unwrap a nil variable, your program will throw an unexpected nil when it encounters an optional exception and crashes. The following explains some techniques for conditional unwrapping:

1.if statement

You can use an if statement to compare the optional parameter with nil to determine if the optional parameter contains a value. You can use comparison operators such as the "equal to" operator (==) or the "not equal to" operator (!=) in the if statement.

Example5: Optional handling with if-else statements

var someValue: Int?
var someAnotherValue: Int! = 0
        
if someValue != nil {
	print("Contains a value \(someValue!)")
}
	print("Does not contain a value")
}
        
if someAnotherValue != nil {
	print("Contains a value \(someAnotherValue!)")
}
	print("Does not contain a value")
}

When the program is run, the output is:

Does not contain a value
Contains value 0

In the above program, if the optional statement contains a value, the code inside the if statement is executed; otherwise, the statements inside the else block are executed. The main disadvantage of using this method for optional handling is that you still need to unwrap the value from the optional using the ! operator.

2.Optional binding (if let)

Optional binding can help you determine if the optional contains a value. If the optional contains a value, it can be used as a temporary constant or variable. Therefore, optional binding can be used with if statements to check the value inside the optional and extract it as a constant or variable in a single operation.

Example5Optional handling with the if let statement

var someValue: Int?
var someAnotherValue: Int! = 0
       
if let temp = someValue {
	print("Contains value \(temp)") 
}
	print("Does not contain a value")
}
        
if let temp = someAnotherValue {
	print("Contains value \(temp)")
}
	print("Does not contain a value")      
}

When the program is run, the output is:

Does not contain a value
Contains value 0

In the above program, if the optional statement contains a value, the code in the if statement is executed. Otherwise, the else block is executed. if-The let statement also automatically unwraps the value and stores the unwrapped value in the temp constant. The main advantage of this method is that although you can be sure that some optional content contains a value, you do not need to force unwrap the value.

3.Guard statement

You can also use the guard statement to handle optional content in Swift. If you don't know what guard is, don't worry. For now, just think of guard as if-There is no condition to prevent else without if. If the condition fails, the else statement is executed. Otherwise, the next statement is executed. For more detailed information, seeSwift Guard.

Example6Optional handling with the Guard statement

func testFunction() {
	let someValue: Int? = 5
	guard let temp = someValue else {
		return
	}
	print("It has some value \(temp)")
}
testFunction()

When the program is run, the output is:

It has some value 5

In the above program, guard contains a condition, that is, whether the optional someValue contains a value. If it contains a value, then guard-The let statement automatically unwraps the value and places the unwrapped value in the temp constant. Otherwise, the else block is executed, and it returns to the calling function. Because the optional contains a value, the print function is called. More details can be found in Swift guard.

4.Nil-coalescing operator (??)

In Swift, you can also use the nil-coalescing operator to check if an optional contains a value. It is defined as (a??b). It expands an optional a, returning it if it contains a value, or returning the default value b if a is nil.

Example7Optional handling with the nil-coalescing operator

var someValue: Int!
let defaultValue = 5
let unwrappedValue: Int = someValue ?? defaultValue
print(unwrappedValue)

When the program is run, the output is:

5

In the above program, the variable someValue is defined as optional and contains a nil value. The nil-coalescing operator cannot unwrap the optional value, so it returns defaultValue. Therefore, the statement print(unwrappedValue) outputs in the console5.

var someValue: Int? = 10
let defaultValue = 5
let unwrappedValue: Int = someValue ?? defaultValue
print(unwrappedValue)

When the program is run, the output is:

10

However, in the above program, the optional variable someValue is initialized with the value10. Therefore, the nil-coalescing operator successfully unwraps the value someValue. Therefore, the statement someValue ?? defaultValue returns in the console10The statement print(unwrappedValue) outputs10.