Swift optional types


Swift's Optional type, used to handle missing values. Optional means "there is a value there and it is equal to x" or "there is no value there".

Swfit language defines suffix? As shorthand for the named type Optional, in other words, the following two declarations are equivalent:

var optionalInteger: Int?
var optionalInteger: Optional<Int>

In both cases, the variable optionalInteger is an optional integer type. Note that between types and ? There is no space between them.

Optional is an enumeration with two cases, None and Some(T), used to indicate that there may or may not be a value. Any type can be explicitly declared as (or implicitly converted to) an optional type. When declaring an optional type, make sure to use parentheses? An appropriate scope for the operator. For example, to declare an optional integer array, you should write it as (Int[])?; if you write it as Int[]?, an error will be reported.

When you declare an optional variable or optional property without providing an initial value, its value will default to nil.

Optional options follow the LogicValue protocol and therefore can appear in a Boolean environment. In this case, if the optional type T? contains any value of type T (that is, its value is Optional.Some(T)), the optional type is equal to true, otherwise it is false.

If an instance of an optional type contains a value, you can use the postfix operator! To access the value as follows:

optionalInteger = 42
optionalInteger! // 42

Use the operator! Retrieving an optional variable with a value of nil will cause a runtime error.

You can use optional chaining and optional binding to selectively perform operations on optional expressions. If the value is nil, no operations will be performed and no runtime error will be reported.

Let us take a detailed look at the following examples to understand the application of optional types in Swift:

import Cocoa

var myString:String? = nil

if myString != nil {
    print(myString)
}else{
    print("字符串为 nil")
}

The execution result of the above program is:

字符串为 nil

The optional type is similar to Objective -The nil value of pointers in C, but nil is only useful for classes, while optional types are available for all types and are safer.


Force parsing

After you are sure that the optional type does contain a value, you can add an exclamation point (!) after the optional name to get the value. This exclamation point means "I know this optional has a value, please use it." This is called forced unwrapping of optional values.

The example is as follows:

import Cocoa

var myString:String?

myString = "Hello, Swift!"

if myString != nil {
   print(myString)
}else{
   print("myString 值为 nil")
}

The execution result of the above program is:

Optional("Hello, Swift!")

Forced parsing of optional values, using the exclamation mark (!):

import Cocoa

var myString:String?

myString = "Hello, Swift!"

if myString != nil {
   // 强制解析
   print( myString! )
}else{
   print("myString 值为 nil")
}

The above program The execution result is:

Hello, Swift!

Note:
Using ! to obtain a non-existent optional value will cause a runtime error. Before using ! to force parsing of a value, be sure the optional contains a value other than nil.


Automatic parsing

You can replace the question mark (?) with an exclamation mark (!) when declaring an optional variable. In this way, the optional variable does not need to add an exclamation point (!) to get the value when using it, it will be automatically resolved.

The example is as follows:

import Cocoa

var myString:String!

myString = "Hello, Swift!"

if myString != nil {
   print(myString)
}else{
   print("myString 值为 nil")
}

The execution result of the above program is:

Hello, Swift!

Optional binding

Use optional binding to determine whether the optional type contains a value. If it does, assign the value to a temporary constant or variable. Optional binding can be used in if and while statements to evaluate optional values ​​and assign the value to a constant or variable.

Write an optional binding in the if statement like the following:

if let constantName = someOptional {
    statements
}

Let’s look at a simple optional binding example:

import Cocoa

var myString:String?

myString = "Hello, Swift!"

if let yourString = myString {
   print("你的字符串值为 - \(yourString)")
}else{
   print("你的字符串没有值")
}

The above program The execution result is:

你的字符串值为 - Hello, Swift!