【问题标题】:Enumeration with raw values使用原始值枚举
【发布时间】:2016-05-27 17:01:44
【问题描述】:

为什么我不能用这样的原始值定义枚举?

enum Edges : (Double, Double) {
    case TopLeft = (0.0, 0.0)
    case TopRight = (1.0, 0.0)
    case BottomLeft = (0.0, 1.0)
    case BottomRight = (1.0, 1.0)
}

【问题讨论】:

    标签: swift rawrepresentable


    【解决方案1】:

    元组不能是枚举的原始值类型。来自The Swift Programming Language

    原始值可以是字符串、字符或任何整数或浮点数类型。

    你可以创建一个自定义的 getter:

    enum Edges {
        case TopLeft, TopRight, BottomLeft, BottomRight
    
        var rawValue: (Double, Double) {
            switch self {
                case .TopLeft: return (0, 0)
                case .TopRight: return (1, 0)
                case .BottomLeft: return (0, 1)
                case .BottomRight: return (1, 1)
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      Because:

      原始值可以是字符串、字符或任何整数或浮点数类型。

      但您有一个替代解决方案:

      enum Edges {
          case TopLeft
          case TopRight
          case BottomLeft
          case BottomRight
      
          func getTuple() -> (Double, Double) {
              switch self {
              case .TopLeft:
                  return (0.0, 0.0)
              case .TopRight:
                  return (1.0, 0.0)
              case .BottomLeft:
                  return (0.0, 1.0)
              case .BottomRight:
                  return (1.0, 1.0)
              }
          }
      }
      
      let a = Edges.BottomLeft
      a.getTuple() // returning (0, 1)
      

      【讨论】:

      • 谢谢这个代码有效。但是你能解释一下每个原始值在其枚举声明中必须是唯一的吗?
      • @Alexander 这意味着您不能创建两个具有相同原始值的不同枚举条目,例如,case TopLeft = 1, case TopRight = 1, case BottomLeft = 3, case BottomRight = 4 是不允许的,因为 1 加倍。
      • 但是我的数据和你的一样,是不是意味着我必须先申报案件?
      • @Alexander 不不不,一切都很好,就像我的回答一样。我包括它只是为了完成。抱歉让你有点困惑。这仅意味着 如果 您为某些枚举定义了自定义 rawValues,那么您不得在该枚举中使用相同的原始值两次。在您的情况下,我们甚至不使用 rawValues,因此已经安全了。
      猜你喜欢
      • 2015-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多