Latest web development tutorials

Swift optional (Optionals) Type

Swift optional (Optional) type, used when handling missing values. Optional means "where there is a value, and it is equal to x" or "there is no value."

Swfit language definition suffix? Optional as a named type of shorthand, in other words, the following two statements are equivalent:

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

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

Optional is an enumeration containing both cases, None and Some (T), is used to indicate it may or may not have value. Any type can be explicitly declared as (or implicit conversion) optional type. When you declare an optional type of time, be sure to use brackets? Operator an appropriate range. For example, an optional integer array declaration, should be written (Int []) ?; written as Int []? Error.

When you declare a variable or optional optional attributes not available when the initial value, its value defaults to nil.

Optional follow LogicValue agreement, it can appear in a boolean context. In this case, if the optional type T? Contain any type of value T (that is to say its value is Optional.Some (T)), this optional type equals true, otherwise it is false.

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

optionalInteger = 42
optionalInteger! // 42

Use operator! To acquire an optional variable is nil there will be run-time errors.

You can use an optional link and an optional bind selectively to perform operations on the optional expression. If the value is nil, no operations are implemented, there will not be run error.

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

import Cocoa

var myString:String? = nil

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

The above program execution results:

字符串为 nil

Optional type is similar to the value of nil pointers in Objective-C, but only to nil class (class) useful but optional for all types of types are available, and more secure.


Forced to resolve

Once you determine the type does contain optional values, you can add an optional name behind an exclamation point (!) To get the value. The exclamation point said, "I know that there are optional values, use it." This is called mandatory optional parsed value (forced unwrapping).

Examples are as follows:

import Cocoa

var myString:String?

myString = "Hello, Swift!"

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

The above program execution results:

Optional("Hello, Swift!")

Forced analytical optional values, use the exclamation point (!):

import Cocoa

var myString:String?

myString = "Hello, Swift!"

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

The above program execution results:

Hello, Swift!

note:
Use ! To get a nonexistent optional values will result in a runtime error. Use ! Before to force the analytical value, you must determine optionally contain a non- nil value.


Automatically parse

You can replace a question mark when you declare a variable optional exclamation mark (!) (?). When using this optional variables you do not need plus an exclamation point (!) To get the value, it will automatically parse.

Examples are as follows:

import Cocoa

var myString:String!

myString = "Hello, Swift!"

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

The above program execution results:

Hello, Swift!

Optional Bind

Using the optional bindings (optional binding) to determine whether an optional type contains the value, if it contains a value assigned to put a temporary variable or constant. Optional binding can be used in if and while statements to judge the value of an optional type and assign a value to a constant or variable.

Like this if statement written in an optional binding:

if let constantName = someOptional {
    statements
}

Let's look at a simple alternative binding instance:

import Cocoa

var myString:String?

myString = "Hello, Swift!"

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

The above program execution results:

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