有可能有专门的通用协议吗?我想要这样的东西:
protocol Protocol: RawRepresentable {
typealias RawValue = Int
...
}这是编译的,但是当我尝试从协议实例访问init或rawValue时,它的类型是RawValue而不是Int。
发布于 2017-09-14 16:46:31
在Swift 4中,可以向协议添加约束:
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 { }https://stackoverflow.com/questions/46224234
复制相似问题