Recently I've saw the WWDC 2015 keynote from Apple. I also looked at some documentation but I can't find a "pattern matching in if" section, how it was written on one of the slides which they have shown. (68min 00sec video from Apple Events)
最近我看到了苹果2015年全球开发者大会的主题演讲。我还查看了一些文档,但是我找不到if部分中的“模式匹配”部分,这部分是如何写在他们展示的其中一张幻灯片上的。(来自苹果事件的68min视频)
Do you know what's this refers to? Or the syntax?
你知道这指的是什么吗?还是语法?
1 个解决方案
#1
58
All it really means is that if statements now support pattern matching like switch statements already have. For example, the following is now a valid way of using if/else if/else statements to "switch" over the cases of an enum.
它真正的意思是if语句现在支持模式匹配,比如switch语句。例如,下面是使用if/else if/else语句在枚举的情况下“切换”的有效方法。
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")
}
And the following is now an acceptable way of checking if someInteger
is within a given range.
下面是一种可以接受的检查某个整数是否在给定范围内的方法。
let someInteger = 42
if case 0...100 = someInteger {
// ...
}
Here are a couple more examples using the optional pattern from The Swift Programming Language
下面是使用Swift编程语言中的可选模式的几个示例
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)
}
#1
58
All it really means is that if statements now support pattern matching like switch statements already have. For example, the following is now a valid way of using if/else if/else statements to "switch" over the cases of an enum.
它真正的意思是if语句现在支持模式匹配,比如switch语句。例如,下面是使用if/else if/else语句在枚举的情况下“切换”的有效方法。
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")
}
And the following is now an acceptable way of checking if someInteger
is within a given range.
下面是一种可以接受的检查某个整数是否在给定范围内的方法。
let someInteger = 42
if case 0...100 = someInteger {
// ...
}
Here are a couple more examples using the optional pattern from The Swift Programming Language
下面是使用Swift编程语言中的可选模式的几个示例
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)
}