问题
Is it possible to have a protocol that specializes a generic protocol? I want something like this:
protocol Protocol: RawRepresentable {
typealias RawValue = Int
...
}
This does compile, but when I try to access the init
or rawValue
from a Protocol instance, its type is RawValue
instead of Int
.
回答1:
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 { }
来源:https://stackoverflow.com/questions/46224234/swift-protocol-specializing-generic-protocol