【问题标题】:Is it possible to declare swift generic for enums of particular type?是否可以为特定类型的枚举声明 swift 泛型?
【发布时间】:2016-01-15 03:43:21
【问题描述】:

是否有可能有一个函数允许 rawValue 是某种类型的任何枚举?例如,任何具有字符串 rawValue 的枚举。

【问题讨论】:

    标签: swift


    【解决方案1】:

    这可以使用泛型和“where”关键字来完成

    enum EnumString: String {
        case A = "test"
    }
    
    func printEnum<T: RawRepresentable where T.RawValue == String>(arg: T) {
        print(arg.rawValue)
    }
    printEnum(EnumString.A) //Prints "test"
    

    【讨论】:

      【解决方案2】:

      您可以声明一个符合 RawRepresentable 类型的泛型,这是一个所有声明原始 rawValue 的枚举都符合的协议。

      enum EnumA: Int {
          case A = 0
      }
      
      enum EnumB {
          case A
      }
      
      func doGenericSomething<T: RawRepresentable>(arg: T) {
          println(arg.rawValue)
      }
      
      doGenericSomething(EnumA.A) //OK
      doGenericSomething(EnumB.A) //Error! Does not conform to protocol RawRepresentable
      

      但是,您不能在泛型中指定枚举的 rawValue 类型。有关信息,您可以查看帖子here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-12-28
        • 2019-01-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多