Reason for assigning optional to new variable in conditional statement in Swift

前端 未结 2 1082
日久生厌
日久生厌 2021-01-05 10:31

I\'m going through the swift docs, and in the optional segment, it talks about using the question mark -- ? -- to signify variables that might be nil. This can

2条回答
  •  情深已故
    2021-01-05 10:50

    Take a look at the section on Optional Chaining in the docs. In the example you cite, there's not much difference. But in other cases, an if-let construction lets you get at an unwrapped value that comes from a series of optional references and method calls, without using implicit unwraps that can crash your app if you haven't considered all the possible bindings for a value in a chain.

    It's also useful if you want to avoid recomputing a value. You can use it in a lot of the same ways you'd use an assignment in a conditional in (Obj)C (remember if (self = [super init])).

    For example, if the optional being tested comes from a computed property:

    var optionalName: String? {
    get {
        if checkTouchID() {
            return "John Appleseed"
        } else {
            return nil
        }
    }
    }
    var greeting = "Hello!"
    if optionalName != nil {
        greeting = "Hello, \(optionalName)"
    }
    

    Paste that into a playground, along with a stub implementation of checkTouchID() that returns true, and you'll immediately see in the results area that the optionalName getter is executing twice. (This would be a problem in a more realistic scenario, because you probably don't want code like this to implicitly checkTouchID() or downloadFromServer() or billApplePay() twice.) If you use an if-let construction instead, you'll only execute the getter once.

    In a series of chained optionals (like if let johnsStreet = john.residence?.address?.street in the docs linked above), you don't want to rewrite the whole chain in the body of the if statement, much less recompute it.

提交回复
热议问题