【问题标题】:Generic RawRepresentable Protocol property通用 RawRepresentable 协议属性
【发布时间】:2017-08-24 18:22:55
【问题描述】:

我希望编写一个protocol,它将与各种测量结构一起使用。这些结构中的每一个都有自己的 Units 枚举,用于定义用于比较的单元类型:

public enum TestUnits: Double {
  case foo = 100.0
  case var = 1000.0
}

所有枚举都是Double 类型并符合RawRepresentable。我正在寻找一种创建通用协议属性的方法,每个Struct 都可以设置自己的单元枚举以进行比较和格式化:

protocol UnitMeasuable {

   var measurementType : SOMETHING<RawRepresentable> { get} 

   func someFormattingFunc(type: measurementType) -> String
}

我只是不清楚如何声明measurementType,以便由单个结构设置。

谢谢

【问题讨论】:

    标签: ios swift struct enums protocols


    【解决方案1】:

    在这种情况下,我会给你两个选择。

    # 在你的协议上使用相关类型

     protocol UnitMeasuable {
     associatedtype Something where Something: RawRepresentable
    
       var measurementType: Something { get} 
       func someFormattingFunc(type: Something) -> String
    }
    

    或者忘记变量(我认为没有理由你应该拥有该属性,但我真的不知道你的计划是什么)并在函数中使用泛型。

    protocol UnitMeasuable {
       func someFormattingFunc<Type: RawRepresentable>(type: Type) -> String
    }    
    

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-15
      • 1970-01-01
      • 2018-08-26
      • 2018-07-15
      • 1970-01-01
      • 2010-12-02
      相关资源
      最近更新 更多