【问题标题】:Swift return associated enum value or nil in one lineSwift 在一行中返回关联的枚举值或 nil
【发布时间】:2017-07-10 09:51:41
【问题描述】:

case 语句并不总是直观的,尤其是在 switch 语句之外。

是否可以在一行中返回枚举案例的关联值如果该案例匹配,否则为零。代码如下:

struct Something<B> {
    enum Base {
        case common(B)
        case extended([B])
    }

    let base:Base

    var common:B? {
        switch base {
        case .common(let common) :
            return common
        default:
            return nil
        }
    }
}

看看common 有很多样板,只是为了返回common 的相关值(如果存在)。我希望语法与此类似(甚至更简单):

var common:B? {
    return case base as .common(let common)
}

(目前使用 Swift 4)

【问题讨论】:

  • 或类似的东西:return (case .common(let common) = base) 对于我正在尝试做的事情来说仍然有点冗长。

标签: ios swift swift4


【解决方案1】:

这有点短

var common:B? {
    if case let .common(common) = base { return common }
    return nil
}

【讨论】:

  • 恐怕这已经是最好的了。也许我会向 Swift 团队提出问题。
  • @DavidJames - 多短才会清晰易读(就像三重关键字 run if case let 的优雅一样)?也许像return case .common(common) ? common : nil 这样的东西适合你?它几乎是 Swift 的,并且具有 C 风格的简洁性。但是 Swift 不支持三元运算符中的模式匹配(该死的正交性?),或者省略 let(所以你知道它不是 var?)。也许你应该接受三重关键字的荣耀? ;-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-14
相关资源
最近更新 更多