我希望写一个protocol,它将与各种测量结构一起使用。这些结构中的每一个都有自己的Units枚举,用于定义要比较的单位类型:
public enum TestUnits: Double {
case foo = 100.0
case var = 1000.0
}我正在寻找一种创建通用协议属性的方法,每个Struct都可以设置自己的单元枚举,以便进行比较和格式化:
protocol UnitMeasuable {
var measurementType : SOMETHING<RawRepresentable> { get}
func someFormattingFunc(type: measurementType) -> String
}我只是不清楚如何声明measurementType,以便它将由单个结构设置。
谢谢
发布于 2018-02-08 11:02:52
在这种情况下,我希望你有两个选择。
在您的协议上使用associatedtype
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
} 希望这能有所帮助!
https://stackoverflow.com/questions/43124425
复制相似问题