Swift 专门化通用协议的协议

Swift protocol specializing generic protocol

是否可以有一个专门针对通用协议的协议?我想要这样的东西:

protocol Protocol: RawRepresentable {
  typealias RawValue = Int
  ...
}

这确实可以编译,但是当我尝试从协议实例访问 initrawValue 时,其类型是 RawValue 而不是 Int

在Swift4中,你可以给你的协议添加约束:

protocol MyProtocol: RawRepresentable where RawValue == Int {
}

现在所有在 MyProtocol 上定义的方法都将有一个 Int rawValue。例如:

extension MyProtocol {
    var asInt: Int {
        return rawValue
    }
}

enum Number: Int, MyProtocol {
    case zero
    case one
    case two
}

print(Number.one.asInt)
// prints 1

采用RawRepresentable但RawValue不是Int的类型不能采用你的约束协议:

enum Names: String {
    case arthur
    case barbara
    case craig
}

// Compiler error
extension Names : MyProtocol { }