Swift 2 - "if" 中的模式匹配

Swift 2 - Pattern matching in "if"

最近看了 Apple 的 WWDC 2015 主题演讲。我还查看了一些文档,但找不到 "pattern matching in if" 部分,它们是如何写在他们展示的其中一张幻灯片上的。 (来自 Apple Events 的 68 分钟 00 秒视频)

你知道这是什么意思吗?还是语法?

它真正的意思是 if 语句现在支持模式匹配,就像 switch 语句已经拥有的那样。例如,以下是现在对枚举的情况使用 if/else if/else 语句 "switch" 的有效方法。

enum TestEnum {
    case One
    case Two
    case Three
}

let state = TestEnum.Three

if case .One = state {
    print("1")
} else if case .Two = state {
    print("2")
} else {
    print("3")
}

下面是检查 someInteger 是否在给定范围内的可接受方法。

let someInteger = 42
if case 0...100 = someInteger {
    // ...
}

这里有几个使用来自 The Swift Programming Language

的可选模式的示例
let someOptional: Int? = 42
// Match using an enumeration case pattern
if case .Some(let x) = someOptional {
    print(x)
}

// Match using an optional pattern
if case let x? = someOptional {
    print(x)
}