可选绑定和 where 子句

选配必须解开他们可以在大多数表达式中使用之前。if let 是一个可选绑定,如果可选值不是 nil 则成功

let num: Int? = 10 // or: let num: Int? = nil

if let unwrappedNum = num {
    // num has type Int?; unwrappedNum has type Int
    print("num was not nil: \(unwrappedNum + 1)")
} else {
    print("num was nil")
}

你可以为新绑定的变量重用相同的名称,遮蔽原始变量:

// num originally has type Int?
if let num = num {
    // num has type Int inside this block
}

Version < 3.0

用逗号(,)组合多个可选绑定:

if let unwrappedNum = num, let unwrappedStr = str {
    // Do something with unwrappedNum & unwrappedStr
} else if let unwrappedNum = num {
    // Do something with unwrappedNum
} else {
    // num was nil
}

使用 where 子句在可选绑定后应用进一步的约束:

if let unwrappedNum = num where unwrappedNum % 2 == 0 {
    print("num is non-nil, and it's an even number")
}

如果你有冒险精神,请交错任意数量的可选绑定和 where 子句:

if let num = num                           // num must be non-nil
    where num % 2 == 1,                    // num must be odd
    let str = str,                         // str must be non-nil
    let firstChar = str.characters.first   // str must also be non-empty
    where firstChar != "x"                 // the first character must not be "x"
{
    // all bindings & conditions succeeded!
}

Version >= 3.0

在 Swift 3 中,where 子句已被替换( SE-0099 ):只需使用另一个 , 来分隔可选绑定和布尔条件。

if let unwrappedNum = num, unwrappedNum % 2 == 0 {
    print("num is non-nil, and it's an even number")
}

if let num = num,                           // num must be non-nil
    num % 2 == 1,                           // num must be odd
    let str = str,                          // str must be non-nil
    let firstChar = str.characters.first,   // str must also be non-empty
    firstChar != "x"                        // the first character must not be "x"
{
    // all bindings & conditions succeeded!
}