【问题标题】:Pattern matching as a functional expression in swift模式匹配作为 swift 中的函数表达式
【发布时间】: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


【解决方案1】:

Switch 语句不能直接用作 Swift 中的表达式。但是,有一种解决方法可以做你想做的事。可以像这样在闭包内编写 switch 语句:

let result : String = {
    switch x {
    case _ where x > 0:
        return "positive"
    case _ where x < 0:
        return "negative"
    default:
        return "zero"
    }
}()

【讨论】:

  • 这是正确答案,刚刚更新为使用where 来检查正负值
  • 谢谢,很整洁
  • 非常聪明,但我不确定为什么有人会想这样做。这比原始示例的可读性差,尤其是当您将可选 var 替换为 let 时,正如@MartinR 所建议的那样。尤其是case_和final()很难看懂。
猜你喜欢
  • 1970-01-01
  • 2019-10-08
  • 2023-03-26
  • 2020-04-29
  • 1970-01-01
  • 2019-05-02
  • 1970-01-01
  • 2012-11-13
  • 2011-12-03
相关资源
最近更新 更多