How in Swift specify type constraint to be enum?

前端 未结 3 1802
情话喂你
情话喂你 2020-12-14 15:18

I want to specify a type constraint that the type should be a raw value enum:

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

class SomeProtocol

        
3条回答
  •  孤城傲影
    2020-12-14 15:42

    AFAIK, Swift does not support type constraint to be specified with enums.

    Cited from Swift Manual

    Type Constraint Syntax

    You write type constraints by placing a single class or protocol constraint after a type parameter’s name, separated by a colon, as part of the type parameter list. The basic syntax for type constraints on a generic function is shown below (although the syntax is the same for generic types):

    Strictly limited to a class or protocol unless there's some hidden features which is not mentioned in manual. As far as I tested, struct or enum are all prohibited by the compiler.

    enum Test1 : Int
    {
        case AAA = 0
    }
    
    func test1f(a: Test1) {}       //  error: Inheritance from non-protocol, non-class type 'Test1'
    
    struct Test2
    {
        var aaa:Int =   0
    }
    
    func test2f(a: Test2) {}       //  error: Inheritance from non-protocol, non-class type 'Test1'
    
    
    class Test3
    {
    }
    
    func test3f(a: Test3) {}       //  OK
    

提交回复
热议问题