Swift protocol specializing generic protocol

858 views Asked by At

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

There are 1 answers

0
Gwendal Roué On BEST ANSWER

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 { }