前端之家收集整理的这篇文章主要介绍了
枚举 – Swift如何指定类型约束为枚举?,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想指定类型约束,类型应该是一个原始值枚举:
enum SomeEnum: Int {
case One,Two,Three
}
class SomeProtocol<E: enum<Int>> { // <- won't compile
func doSomething(e: E) {
compute(e.toRaw())
}
}
我怎么能在斯威夫特呢? (我用F#语法为例)
@H_
404_6@
enum SomeEnum: Int {
case One,Three
}
class SomeClass<E: RawRepresentable where E.RawValue == Int>{
func doSomething(e: E) {
print(e.rawValue)
}
}
class SomeEnumClass : SomeClass<SomeEnum> {
}
或直接
class SomeOtherClass{
func doSomething<E: RawRepresentable where E.RawValue == Int>(e: E) {
print(e.rawValue)
}
}
swift3的更新:
enum SomeEnum: Int {
case One,Three
}
class SomeClass<E: RawRepresentable> where E.RawValue == Int {
func doSomething(e: E) {
print(e.rawValue)
}
}
class SomeEnumClass : SomeClass<SomeEnum> {
}
RESP。
class SomeOtherClass{
func doSomething<E: RawRepresentable>(e: E) where E.RawValue == Int {
print(e.rawValue)
}
}