如何在Swift中指定类型约束为枚举?

Alf*_*a07 30 enums swift

我想指定一个类型约束,类型应该是原始值枚举:

enum SomeEnum: Int {
  case One, Two, Three
}

class SomeProtocol<E: enum<Int>> { // <- won't compile
    func doSomething(e: E) {
        compute(e.toRaw())
    }
}
Run Code Online (Sandbox Code Playgroud)

我怎么能在Swift中做到这一点?(我以F#语法为例)

JMI*_*JMI 61

enum SomeEnum: Int {
    case One, Two, Three
}

class SomeClass<E: RawRepresentable where E.RawValue == Int>{
    func doSomething(e: E) {
        print(e.rawValue)
    }
}

class SomeEnumClass : SomeClass<SomeEnum> {

}
Run Code Online (Sandbox Code Playgroud)

或直接

class SomeOtherClass{
    func doSomething<E: RawRepresentable where E.RawValue == Int>(e: E) {
        print(e.rawValue)
    }
}
Run Code Online (Sandbox Code Playgroud)

更新swift3:

enum SomeEnum: Int {
    case One, Two, Three
}

class SomeClass<E: RawRepresentable> where E.RawValue == Int {
    func doSomething(e: E) {
        print(e.rawValue)
    }
}

class SomeEnumClass : SomeClass<SomeEnum> {

}
Run Code Online (Sandbox Code Playgroud)

RESP.

class SomeOtherClass{
    func doSomething<E: RawRepresentable>(e: E) where E.RawValue == Int {
        print(e.rawValue)
    }
}
Run Code Online (Sandbox Code Playgroud)


Sul*_*han 11

虽然您可以将枚举放入没有<T>约束()的泛型类型,但是不可能为所有枚举或所有结构创建约束.所有约束都基于接口(子类化,协议).不幸的是,两个随机结构或两个随机枚举之间没有任何共同之处.

结构和枚举不能从其他结构/枚举继承,因此枚举的唯一约束必须基于协议.

protocol EnumProtocol {
    func method()
}

enum TestEnum : Int, EnumProtocol {
    case A
    case B

    func method() {
    }
}

enum TestEnum2 : Int, EnumProtocol {
    case C

    func method() {
    }
}

class EnumGeneric <T : EnumProtocol> {
    func method(a: T) {
       a.method()
    }
}

let test = EnumGeneric<TestEnum>()
test.method(TestEnum.A)
Run Code Online (Sandbox Code Playgroud)

另请注意,所有枚举"继承"原始类型都Int符合RawRepresentable,所以你可以

class EnumGeneric <T : RawRepresentable> {
    func method(a: T) {
       println("\(a.toRaw())");
    }
}
Run Code Online (Sandbox Code Playgroud)

但这对于声明为枚举的枚举不起作用 enum TestEnum {


Eon*_*nil 4

AFAIK,Swift 不支持使用枚举指定类型约束。

\n\n

引用自Swift 手册

\n\n
\n

类型约束语法

\n\n

您可以通过在类型参数\xe2\x80\x99 名称后面放置一个类或协议约束来编写类型约束,并用冒号分隔,作为类型参数列表的一部分。泛型函数的类型约束的基本语法如下所示(尽管泛型类型的语法相同):

\n
\n\n

严格限于某个类或协议,除非有一些手册中未提及的隐藏功能。据我测试,struct还是enum都被编译器禁止了。

\n\n
enum Test1 : Int\n{\n    case AAA = 0\n}\n\nfunc test1f<T:Test1>(a: Test1) {}       //  error: Inheritance from non-protocol, non-class type \'Test1\'\n\nstruct Test2\n{\n    var aaa:Int =   0\n}\n\nfunc test2f<T:Test2>(a: Test2) {}       //  error: Inheritance from non-protocol, non-class type \'Test1\'\n\n\nclass Test3\n{\n}\n\nfunc test3f<T:Test3>(a: Test3) {}       //  OK\n
Run Code Online (Sandbox Code Playgroud)\n