What is optional

Optionals is a feature unique to Swift, also known as optionals, similar to OC methods that return nil or return an object. Nil in OC applies only to objects, not constructs, primitive C types, or enumerated values. For these types, objective-C methods usually return a special value (such as NSNotFound) to indicate that there is no value. Swift’s optionals can indicate the presence or absence of any type of value, without requiring a special constant. If a constant or variable in your code needs to handle missing values under certain conditions, declare it as an optional type.

Var serverResponseCode: int? = 404 // Contains no values serverResponseCode = nilCopy the code

The question mark indicates that the value it contains is optional, which means that it may contain some Int values or no value at all. You cannot use nil for non-optional constants and variables.

Nil the difference between Swift and OC

Nil for Swift is not the same as nil in Objective-C. In Objective-C, nil is a pointer to an object that doesn’t exist. In Swift, nil is not a pointer; it is the absence of a value of a particular type. Any type of Optionals can be set to nil, not just the object type.

Optional applications

Swift’s Int type has an initializer that attempts to convert a string value to an Int value. However, not every string can be converted to an integer. The string “123” can be converted to a numeric value of 123, but the string “hello, world” has no obvious numeric value to convert. The following example attempts to convert a string to an Int:

let possibleNumber = "123"
let convertedNumber = Int(possibleNumber)
Copy the code

Because the conversion may fail, it returns a convertedNumber that is an optional integer rather than an integer. For optional types, you need to unpack them in the following way.

Mandatory parsing

Once you determine that the optional does contain values, you can do this by adding an exclamation mark (!) to the end of the optional name. To access its underlying value. This is called forced expansion of optional values:

if convertedNumber != nil {
    print("convertedNumber has an integer value of \(convertedNumber!).")
}
Copy the code

This is an unsafe way to unpack if used! Accessing optional values that do not exist will trigger a runtime error. Make sure an optional value is non-nil before using it.

Optional binding

if let actualNumber = Int(possibleNumber) {
    print("The string \"\(possibleNumber)\" has an integer value of \(actualNumber)")
} else {
    print("The string \"\(possibleNumber)\" could not be converted to an integer")
}
Copy the code

If the optional integer returned by Int(possibleNumber) has a value, a new constant named actualNumber is set to the value contained in the optional integer.

If the conversion succeeds, you can use the actualNumber constant in the If statement. If you want to operate on the value of actualNumber in the first branch of an If statement, you can write If var actualNumber, and the value contained in the optional statement will be available as a variable rather than a constant.

Implicit solution package

Sometimes it is obvious that an optional value must have a value the first time it is assigned, so it can be defined as an implicitly expanded optional value. By placing an exclamation mark (string!) after the type you want to make optional. Instead of a question mark (string?) , you do not need to put an exclamation mark after its name.

An implicitly expanded optional value is a normal optional value behind the scenes, but can also be used as a non-optional value without having to expand it every time the optional value is accessed. The following example shows the difference in behavior between an optional string and an implicitly expanded optional string when accessing its wrapped value as an explicit string:

let possibleString: String? = "An optional string."
let forcedString: String = possibleString! // requires an exclamation point

let assumedString: String! = "An implicitly unwrapped optional string."
let implicitString: String = assumedString // no need for an exclamation point
Copy the code

In the above code, the optional value assumedString is forcibly unwrapped before assigning its value to implicitString, because implicitString has an explicit, non-optional string type. In the following code, optionalString does not have an explicit type, so it is a common optional type:

let optionalString = assumedString
// The type of optionalString is "String?" and assumedString isn't force-unwrapped.
Copy the code

OptionalString is of type “String?” And assumedString is not forcibly unwrapped.

If an implicitly expanded optional object is nil and you try to access its wrapper value, a runtime error will be raised. The result is exactly the same as placing an exclamation mark after a normal optional option that contains no value. It is possible to check if an implicitly expanded optional object is nil, just as it is for a normal optional object:

if assumedString ! = nil { print(assumedString!) }Copy the code

You can also use optional bindings to implicitly unpack:

if let definiteString = assumedString {
    print(definiteString)
}
Copy the code

Docs.swift.org/swift-book/…