Swift protocol specializing generic protocol

前端 未结 1 1955
一向
一向 2021-01-29 03:20

Is it possible to have a protocol that specializes a generic protocol? I want something like this:

protocol Protocol: RawRepresentable {
  typealias RawValue = I         


        
相关标签:
1条回答
  • 2021-01-29 03:44

    In Swift 4, you can add constraints to your protocol:

    protocol MyProtocol: RawRepresentable where RawValue == Int {
    }
    

    And now all methods defined on MyProtocol will have an Int rawValue. For example:

    extension MyProtocol {
        var asInt: Int {
            return rawValue
        }
    }
    
    enum Number: Int, MyProtocol {
        case zero
        case one
        case two
    }
    
    print(Number.one.asInt)
    // prints 1
    

    Types that adopt RawRepresentable but whose RawValue is not Int can not adopt your constrained protocol:

    enum Names: String {
        case arthur
        case barbara
        case craig
    }
    
    // Compiler error
    extension Names : MyProtocol { }
    
    0 讨论(0)
提交回复
热议问题