Swift optional type


Release date:2023-11-24 Update date:2023-12-08 Editor:admin View counts:135

Label:

Swift optional type

The optional (Optional) type of Swift, which is used to handle cases where values are missing. Optional means “there is a value, and it is equal to x” or “there is no value”.

Swfit language definition suffix? As an abbreviation for named type Optional, in other words, the following two declarations are equal:

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

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

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 (or implicitly converted) as an optional type. When declaring an optional type, be sure to give it in parentheses. An appropriate range of operators. For example, declare an array of optional integers, which should be written as (Int [])? write Int[] ? Will make a mistake.

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

Optional compliance with the LogicValue protocol, so it 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) this optional type is equal to true instead of being regarded as 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 operators! To get an optional variable with a value of nil will have a run-time error.

You can optionally perform operations on optional expressions with optional links and optional bindings. If the value is nil no action will be performed, and no run error will be reported

Let’s take a closer 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("The string is nil")
}

The execution results of the above procedures are as follows:

The string is nil

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

Forced parsing

When you are sure that the optional type does contain a value, you can get the value by adding an exclamation point (!) after the optional name. The exclamation point says, “I know this optional value, please use it.” This is called forced parsing of optional values (forced unwrapping).

Examples are as follows:

import Cocoa

var myString:String?

myString = "Hello, Swift!"

if myString != nil {
   print(myString)
}else{
   print("myString value is nil")
}

The execution results of the above procedures are as follows:

Optional("Hello, Swift!")

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

import Cocoa

var myString:String?

myString = "Hello, Swift!"

if myString != nil {
   // Forced parsing
   print( myString! )
}else{
   print("myString value is nil")
}

The execution results of the above procedures are as follows:

Hello, Swift!

Note: use th ! to get an optional value that does not exist will cause a run-time error. Use ! before you force the parsing value, be sure to optionally include a non- nil the value.

Automatic parsing

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

Examples are as follows:

import Cocoa

var myString:String!

myString = "Hello, Swift!"

if myString != nil {
   print(myString)
}else{
   print("myString value is nil")
}

The execution results of the above procedures are as follows:

Hello, Swift!

Optional binding

Use optional bindings (optional binding) to determine whether the optional type contains a value, and if so, assign the value to a temporary constant or variable. Optional bindings can be used in the if and while statement to determine the value of the optional type and assign the value to a constant or variable.

Write an optional binding in the if statement as follows:

if let constantName = someOptional {
    statements
}

Let’s look at the next example of a simple optional binding:

import Cocoa

var myString:String?

myString = "Hello, Swift!"

if let yourString = myString {
   print("Your string value is - \(yourString)")
}else{
   print("Your string value is")
}

The execution results of the above procedures are as follows:

Your string value is - Hello, Swift!

Powered by TorCMS (https://github.com/bukun/TorCMS).