专门化通用协议的Swift协议
是否可能有专门针对通用协议的协议?我想要这样的东西:专门化通用协议的Swift协议,swift,generics,inheritance,protocols,specialization,Swift,Generics,Inheritance,Protocols,Specialization,是否可能有专门针对通用协议的协议?我想要这样的东西: protocol Protocol: RawRepresentable { typealias RawValue = Int ... } 这是可以编译的,但是当我尝试从协议实例访问init或rawValue时,它的类型是rawValue,而不是Swift 4中的Int,您可以为协议添加约束: protocol MyProtocol: RawRepresentable where RawValue == Int { } enum N
protocol Protocol: RawRepresentable {
typealias RawValue = Int
...
}
这是可以编译的,但是当我尝试从协议实例访问
init
或rawValue
时,它的类型是rawValue
,而不是Swift 4中的Int
,您可以为协议添加约束:
protocol MyProtocol: RawRepresentable where RawValue == Int {
}
enum Names: String {
case arthur
case barbara
case craig
}
// Compiler error
extension Names : MyProtocol { }
现在,在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的类型不能采用受约束的协议:
protocol MyProtocol: RawRepresentable where RawValue == Int {
}
enum Names: String {
case arthur
case barbara
case craig
}
// Compiler error
extension Names : MyProtocol { }
在Swift 4中,您可以向协议添加约束:
protocol MyProtocol: RawRepresentable where RawValue == Int {
}
enum Names: String {
case arthur
case barbara
case craig
}
// Compiler error
extension Names : MyProtocol { }
现在,在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的类型不能采用受约束的协议:
protocol MyProtocol: RawRepresentable where RawValue == Int {
}
enum Names: String {
case arthur
case barbara
case craig
}
// Compiler error
extension Names : MyProtocol { }
您正在尝试创建一个仅适用于具有
Int
原始值的枚举的协议?您找不到更好的协议名称吗?您正在尝试创建一个仅适用于具有Int
原始值的枚举的协议?您找不到更好的协议名称吗?