可選繫結和 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!
}