对于简单的情况,如果让我或看起来没有看到优势, if case let x? = someOptional where ... { ...}//I don't see the advantage over the original if letif let x = someOptional where ... { ...} 对于for-case-let案例来简化可选
if case let x? = someOptional where ... {
...
}
//I don't see the advantage over the original if let
if let x = someOptional where ... {
...
}
对于for-case-let案例来简化可选集合的使用,我真的希望swift可以更进一步:
for case let x? in optionalArray {
...
}
//Wouldn't it be better if we could just write
for let x? in optionalArray {
...
}
谷歌一段时间之后,我发现有用的唯一案例就是这个“Swift 2 Pattern Matching: Unwrapping Multiple Optionals”:
switch (username, password) {
case let (username?, password?):
print("Success!")
case let (username?, nil):
print("Password is missing")
...
那么引入可选模式的任何其他优点呢?
我相信你把两个不同的概念混为一谈.不可否认,语法不是直观的,但我希望它们的用法在下面说明.(我建议阅读关于 Patterns in The Swift Programming Language的页面.)
案件条件
“案件条件”是指写作的能力:
>如果案例«pattern»=«expr»{…}
>虽然案例«模式»=«expr»{…}
>对于案例«pattern»in«expr»{…}
这些特别有用,因为它们允许您在不使用switch的情况下提取枚举值.
你的例子,如果情况让x? = someOptional …,是一个有效的例子,但我相信它对除了Optional之外的枚举最有用.
enum MyEnum {
case A
case B(Int)
case C(String)
}
func extractStringsFrom(values: [MyEnum]) -> String {
var result = ""
// Without case conditions, we have to use a switch
for value in values {
switch value {
case let .C(str):
result += str
default:
break
}
}
// With a case condition, it's much simpler:
for case let .C(str) in values {
result += str
}
return result
}
实际上,您可以使用几乎任何通常在交换机中使用的模式的案例条件.有时可能很奇怪:
>如果case,则让str为String = value {…}(相当于如果让str = value为?String)
>如果case是String = value {…}(相当于if值是String)
>如果情况1 … 3 =值{…}(相当于if(1 … 3).contains(value)或者如果1 … 3~ = value)
可选模式,a.k.a.让x?
另一方面,可选模式是一种模式,除了简单的let之外,它还允许您在上下文中解包选项.它在交换机中使用时特别有用(类似于您的用户名/密码示例):
func doSomething(value: Int?) {
switch value {
//case 2: // Not allowed
case 2?:
print("found two")
case nil:
print("found nil")
case let x:
print("found a different number: \(x)")
}
}
