【发布时间】:2016-01-15 03:43:21
【问题描述】:
是否有可能有一个函数允许 rawValue 是某种类型的任何枚举?例如,任何具有字符串 rawValue 的枚举。
【问题讨论】:
标签: swift
是否有可能有一个函数允许 rawValue 是某种类型的任何枚举?例如,任何具有字符串 rawValue 的枚举。
【问题讨论】:
标签: swift
这可以使用泛型和“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"
【讨论】:
您可以声明一个符合 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。
【讨论】: