How is optional binding used in swift?

前端 未结 9 2695
太阳男子
太阳男子 2020-12-10 13:07

In swift the following syntax is allowed for flow control

if let constantName = someOptional {
    statements
}

In this context wh

相关标签:
9条回答
  • 2020-12-10 13:24

    In Swift 1.2 and 2.1, you can do this:

    if let constantName = someOptional, constantName2 = someOptional2 {
        // statements
    }
    
    0 讨论(0)
  • First someOptional is checked to see if it's nil or has data. If it's nil, the if-statement just doesn't get executed. If there's data, the data gets unwrapped and assigned to constantName for the scope of the if-statement. Then the code inside the braces is executed.

    if let constantName = someOptional {
        statements
    }
    

    There's no way to chain this functionality in one if-statement. let constantName = someOptional does not directly evaluate to a boolean. It's best to think of "if let" as a special keyword.

    0 讨论(0)
  • 2020-12-10 13:30

    Think of it like this: An optional is just an Enum with an associated value.

    enum OptionalValue<T> {
        case None
        case Some(T)
    }
    

    When you assign to an optional, under the hood the .Some enum value is used, with an associated value that you gave. If you assign it to nil, it's given the value None, with no associated value.

    if let constantName = someOptional {}
    

    Does the if on the enum. If it's .Some, then the constant is assigned the associated value, and the block is executed. Otherwise nothing happens.

    0 讨论(0)
提交回复
热议问题