对于像我这样的简单案例,if let
或guard
我看不到优势,
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模式匹配:展开多个可选内容”:
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 ...
是一个有效的示例,但是我相信,除了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
}
实际上,您可以将案例条件与通常在.NET中使用的几乎任何模式一起使用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)
或if 1...3 ~= value
)let x?
另一方面,可选模式是一种模式,可让您在除simple之外的上下文中解开可选选项if let
。使用时,它是特别有用的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)")
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句