如何在单个 if 条件中使用可选的展开和布尔条件

How to use optional unwrapping and a boolean condition in a single if condition

我想在单个语句中检查对象是否为 NSNumber 类型并且布尔变量是否为 true 类型。 为此,我写如下:

let someBool = ...
if value.isKindOfClass(NSDictionary) {
   // do something with dict
}
else if (let number = value as? NSNumber) && someBool{
  //Do something with number
}
else {
  // do something here
}

但是,它的抛出错误类似于 'pattern variable binding cannot appear in an expression'。

如何在单个 if 条件中使用可选的展开和布尔条件?

您可以使用 where 子句:

if let number = value as? NSNumber where someBool {
    // ...
}

ABakerSmith 的回答很完美。

我只想分享如何使用强大的 Swift switch 语句实现相同的结果。

switch value {
case let dictionary as NSDictionary:
    println("do something with dictionary")
case let number as NSNumber where someBool:
    println("do something with number")
default: println("do something here")
}