必须先拆开可选选项,然后才能在大多数表达式中使用它们。if let是一个可选绑定,如果可选值不是nil,则绑定成功:
let num: Int? = 10 //或:let num:整数?=无
if let unwrappedNum = num {
//num类型为Int ?; unwrappedNum类型为Int
print("num was not nil: \(unwrappedNum + 1)")
} else {
print("num was nil")
}您可以为新绑定的变量重用相同的名称,以隐藏原始变量:
// num最初具有Int类型?
if let num = num {
// num在此块中的类型为Int
}将多个可选的绑定与逗号(,)结合使用:
if let unwrappedNum = num, let unwrappedStr = str {
// 用unwrappedNum做某事 & unwrappedStr
} else if let unwrappedNum = num {
// 用unwrappedNum做某事
} else {
// num为零
}使用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必须为非nil
where num % 2 == 1, // num必须是奇数
let str = str, // str必须为非null
let firstChar = str.characters.first // str也必须为非空
where firstChar != "x" // 第一个字符不能为“ x”"x"
{
// all bindings & conditions succeeded!
}在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必须为非nil
num % 2 == 1, // num必须是奇数
let str = str, // str必须为非null
let firstChar = str.characters.first, // str也必须为非空
firstChar != "x" // 第一个字符不能为“ x”"x"
{
// all bindings & conditions succeeded!
}