Swift Optionals
Swift's optional (Optional) type is used to handle missing values. Optional means "there is a value, and it equals x" or "there is no value."
The Swift language defines the 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 the type and?there is no space.
Optional is an enumeration with two cases, None and Some(T), used to represent a value that may or may not exist. Any type can be explicitly declared (or implicitly converted) as an optional type. When declaring an optional type, make sure to use parentheses to give the ? operator an appropriate scope. For example, to declare an optional integer array, you should write (Int[])?; writing Int[]? will cause an error.
When you declare an optional variable or optional property without providing an initial value, its value defaults to nil.
Optionals conform to the LogicValue protocol, so they can appear in a boolean context. In this case, if an optional type T? contains any value of type T (that is, its value is Optional.Some(T)), the optional 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 that value, as shown below:
optionalInteger = 42 optionalInteger! // 42
Using the operator ! to access an optional variable whose value is 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 operation is performed, and there is no runtime error.
Let's 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 output of the above program is:
字符串为 nil
Optional types are similar to the nil value of pointers in Objective-C, but nil is only useful for classes, while optional types are available for all types and are safer.
Forced Unwrapping
When you are sure that the optional type actually contains a value, you can add an exclamation mark (!) after the optional's name to access the value. This exclamation mark means "I know this optional has a value, please use it." This is called forced unwrapping of an optional value.
Example below:
import Cocoa
var myString:String?
myString = "Hello, Swift!"
if myString != nil {
print(myString)
}else{
print("myString 值为 nil")
}
The output of the above program is:
Optional("Hello, Swift!")
Force unwrapping an optional value using the exclamation mark (!):
import Cocoa
var myString:String?
myString = "Hello, Swift!"
if myString != nil {
// 强制解析
print( myString! )
}else{
print("myString 值为 nil")
}
The output of the above program is:
Hello, Swift!
Note:
Using!to access a non-existent optional value will cause a runtime error. Using!before force unwrapping a value, be sure that the optional contains a non-nilvalue.
Automatic Unwrapping
You can use an exclamation mark (!) instead of a question mark (?) when declaring an optional variable. This way, the optional variable does not need to add an exclamation mark (!) to access the value when used; it will be unwrapped automatically.
Example below:
import Cocoa
var myString:String!
myString = "Hello, Swift!"
if myString != nil {
print(myString)
}else{
print("myString 值为 nil")
}
The output of the above program is:
Hello, Swift!
Optional Binding
Use optional binding to determine whether an optional type contains a value. If it contains a value, assign that value to a temporary constant or variable. Optional binding can be used in if and while statements to check the value of an optional type and assign the value to a constant or variable.
Write an optional binding in an if statement as follows:
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 output of the above program is:
你的字符串值为 - Hello, Swift!Other Extensions