【发布时间】:2015-10-20 15:15:38
【问题描述】:
Swift 是一门漂亮的函数式语言,而函数式语言都是关于表达式而不是语句的,这就是为什么 switch 模式匹配让我感到困惑。
所有的例子都是这样的:
switch x {
case > 0:
print("positive")
case < 0:
print("negative")
case 0:
print("zero")
}
但我想做这样的事情:
let result = switch x {
case > 0:
"positive"
case < 0:
"negative"
case 0:
"zero"
}
目前我能看到的唯一方法是:
var result: String?
switch x {
case > 0:
result = "positive"
case < 0:
result = "negative"
case 0:
result = "zero"
}
if let s = result {
//...
}
这显然没有基于“表达式”的 switch 语句那么优雅。是否有任何解决方法或替代方案,或者这是苹果需要做些什么来增强语言?
【问题讨论】:
-
请注意,在上一个示例中您不需要可选项,您可以声明
let result: String。编译器验证是否在之前使用变量。 -
谢谢马丁我不知道
标签: swift functional-programming switch-statement pattern-matching expression