【问题标题】:Is there a way to define a swift enum with power of 2 (or calculated value)有没有办法用 2 的幂(或计算值)定义一个快速枚举
【发布时间】:2016-04-29 13:16:59
【问题描述】:

有没有办法在 Swift 2 中做这样的事情?

enum Placement: Int, OptionSetType {
    case
    Left   = 1 << 0,
    Right  = 1 << 1,
    Center = 1 << 2,
    Top    = 1 << 3,
    Bottom = 1 << 4,
    Middle = 1 << 5
    ;
    ....
}

实际的问题是编译器不够聪明,无法看到这些值是常量,但比结果更具可读性。

那么,是否有一些语法糖允许这样的声明?

【问题讨论】:

标签: swift enums swift2


【解决方案1】:

正如@Martin R 所说,你需要结构。

struct Placement: OptionSetType {
    let rawValue: Int

    init(rawValue: Int) {
        self.rawValue = rawValue
    }

    static let Left = Placement(rawValue: 1 << 0)
    static let Right = Placement(rawValue: 1 << 1)
    static let Center = Placement(rawValue: 1 << 2)
    static let Top = Placement(rawValue: 1 << 3)
}

【讨论】:

  • 对每个常量使用let 值而不是var 不是更好吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-17
  • 1970-01-01
  • 2013-05-31
  • 2012-03-21
相关资源
最近更新 更多