Swift protocol specializing generic protocol

流过昼夜 提交于 2020-02-08 07:34:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!