Swift optional (Optionals) type

Swift's optional (Optional) type to handle missing values. Optionally, "there's a value there, and it's equal to x" or "There's no value there."

Swfit language definition suffix? As a short case of the naming type Optional, in other words, the following two declarations are equal:

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

In both cases, the variable optionInteger is an optional integer type. N ote that in type and? T here are no spaces between them.

Optional is an enumeration of two conditions, None and Some(T), that indicate that there may or may not be a value. A ny type can be explicitly declared (or implicitly converted) as optional. W hen declaring an optional type, make sure you give it in parentheses. T he operator has a suitable range. F or example, declaring an optional array of integers should be written as (Int)?

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

Options follow the LogicValue protocol, so they can appear in Boolean environments. I n this case, if the optional type T? contains any value of the type T (that is, its value is Option.Some(T), the optional type is equal to true and the reverse is false.

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

optionalInteger = 42
optionalInteger! // 42

Use the operator! T here is a run-time error to get an optional variable with a value of nil.

You can selectively perform actions on optional expressions with optional links and optional bindings. I f the value is nil, no action will be performed and no errors will be reported.

Let's take a look at the following examples to learn about the optional types of apps in Swift:

import Cocoa

var myString:String? = nil

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

The above procedures are performed as follows:

字符串为 nil

The optional type is similar to the nil value of the pointer in Objective-C, but the nil is only useful for class, and the optional type is available for all types and is more secure.


Force resolution

Once you're sure that the optional type does contain a value, you can add an exclamation point (!) to the optional name to get the value. T his exclamation point says, "I know this optional value, please use it." "This is called forced unwrapping for optional values.

Here's an example:

import Cocoa

var myString:String?

myString = "Hello, Swift!"

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

The above procedures are performed as follows:

Optional("Hello, Swift!")

Force resolution of optional values, using an exclamation point (!):

import Cocoa

var myString:String?

myString = "Hello, Swift!"

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

The above procedures are performed as follows:

Hello, Swift!

Attention:
Use ! T o get an optional value that does not exist causes a runtime error. U se ! Before you force a resolution of a value, be sure to make sure that you can optionally include nil


Automatic resolution

You can replace the question mark (?) with an exclamation point (!) when declaring an optional variable. This way, the optional variable does not need to add an exclamation point (!) to get the value when it is used, and it resolves automatically.

Here's an example:

import Cocoa

var myString:String!

myString = "Hello, Swift!"

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

The above procedures are performed as follows:

Hello, Swift!

Optional binding

Use optional binding to determine whether the optional type contains a value and, if so, assign the value to a temporary constant or variable. O ptional bindings can be used in if and while statements to judge values of optional types and assign values to a constant or variable.

Write an optional binding in an if statement like this:

if let constantName = someOptional {
    statements
}

Let's look at the next simple example of an optional binding:

import Cocoa

var myString:String?

myString = "Hello, Swift!"

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

The above procedures are performed as follows:

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