SoFunction
Updated on 2025-04-11

Learning notes for chain call of Optional value in Swift

The Optional value in Swift has the characteristic that when it is optionally unpacked, that is, when using ? to take the Optional type value, if the Optional value is not nil, the data value of the original type will be returned, and if it is nil, it will be returned. Therefore, when using ? to unpack Optional method, attribute or subscript, if there is a value, it will be called successfully. If there is no value, it will fail and nil will be returned.

Note: When using!, forced unpacking will be performed. If the Optional value is nil, a runtime error will occur. Therefore, when the developer uses! for forced unpacking, he must confirm that the Optional type value is not nil.

When optional unpacking an optional value and calling its attributes or methods, no matter what type of original attribute or method return value is, it will be wrapped as an Optional value type. When using ? to unpack an Optional value and call its method, the return value of the method will be wrapped as an Optional type, as shown below:

class Myclass {
  var cls:MyClassTwo?
  
}
class MyClassTwo {
  func run() -> String {
    return "run"
  }
}

let obj:Myclass = Myclass()
//Nil will be returned?.run()

When making Optional chain calls,It will follow some of the following characteristics:

1. If the properties or method return value of the Optional value are unpacked as non-Optional value, it will be wrapped into an Optional value.

2. If the Optional value property or method return value is originally an Optional value, the Optional value will still be returned, and the Optional value will not be nested.

3. Since the Optional value? When using the optional unpacking, the return value of its properties and method will be wrapped as Optional type, so using Optional chain call can be made. During this period, if a link is called, the entire chain will return nil.

Examples are as follows:

let obj:Myclass = Myclass()
//Nil will be returned(?.run())?.startIndex