对于像这样的简单情况if let
or guard
没看出优点啊
if case let x? = someOptional where ... {
...
}
//I don't see the advantage over the original if let
if let x = someOptional where ... {
...
}
For the 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 模式匹配:展开多个可选值" :
switch (username, password) {
case let (username?, password?):
print("Success!")
case let (username?, nil):
print("Password is missing")
...
那么引入可选模式还有其他优点吗?
我相信您正在混淆两个不同的概念。诚然,语法并不是很直观,但我希望下面能澄清它们的用途。
(我建议阅读有关页面模式在Swift 编程语言.)
case
状况
“案例条件”是指能够编写:
if case «pattern» = «expr» { ... }
while case «pattern» = «expr» { ... }
for case «pattern» in «expr» { ... }
这些特别有用,因为它们可以让您提取枚举值不使用switch
.
你的例子,if case let x? = someOptional ...
,是一个有效的例子,但我相信它最有用除了可选之外的枚举.
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 条件与通常在 a 中使用的几乎任何模式一起使用switch
。有时可能会很奇怪:
-
if case let str as String = value { ... }
(相当于if let str = value as? String
)
-
if case is String = value { ... }
(相当于if value is String
)
-
if case 1...3 = value { ... }
(相当于if (1...3).contains(value)
or if 1...3 ~= value
)
可选模式,又名let x?
另一方面,可选模式是一种允许您在简单的上下文中展开选项的模式。if let
。使用时特别有用in a switch
(类似于您的用户名/密码示例):
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)")
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)