Chaining calls to the Optional value in Swift study notes

  • 2020-05-17 06:37:56
  • OfStack

The Optional value in Swift has the property that when it is optionally unpacked, ? When evaluating values of type Optional, if the value of Optional is not nil, the data value of the original type will be returned, and if the value is nil, nil will be returned. Therefore, when using ? When a method, property, or subscript is called on Optional after unpacking, if there is a value, the corresponding call will succeed; if there is no value, the call will fail and nil will be returned.

Note: use! If the Optional value is nil, a runtime error will occur, so the developer is using! When forced unpacking, you must make sure that the Optional type value is not nil.

When an optional value is optionally unwrapped and its property or method is called, it is wrapped as an Optional value type, regardless of the type of the original property or method return value. When using the & # 63; When an Optional value is unpacked and its method is called, the method's return value 1 is wrapped as Optional type, as shown below:


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

let obj:Myclass = Myclass()
// Will return nil
obj.cls?.run()

When making an Optional chain call, the following features are observed:

1. If proceed ? Unpacking the property or method return value of the Optional value, which was originally a non-Optional value, wraps it as an Optional value.

2. If proceed ? Unpacking an Optional value from a property or method that originally had an Optional value will still return an Optional value and will not nest the Optional value type.

3. Due to the use of Optional values. Optional unpacking wraps the return values of its properties and methods as Optional, so use ? You can make a chain call to Optional, during which one of the links fails and the whole chain returns nil.

Here's an example:


let obj:Myclass = Myclass()
// Will return nil
(obj.cls?.run())?.startIndex


Related articles: