What determines priority in protocol conformance?

Viewed 84

just curious about something.

private enum CodingKeys: String, CodingKey {
    case id = "page"
}

If I were to place String after the CodingKey protocol I would get an error saying I need to place String before.. well what determines the priority and why does that even matter? Thanks in advance.

2 Answers

Protocol conformance order does not matter. In your case you are getting an error when you place String after CodingKey is because String is not a protocol. It is a struct. Look at the error message what you get in Xcode:

Raw type 'String' must appear first in the enum inheritance clause

By placing String after the enum declaration will define its raw value.

To prove the point let's define two protocols:

protocol Protocol1 { }

protocol Protocol2 { }

And try to change the order they conform to your CodingKeys enum. This would be valid:

private enum CodingKeys: String, CodingKey, Protocol1, Protocol2 {
    case id = "page"
}

And this is valid too:

private enum CodingKeys: String, CodingKey, Protocol2, Protocol1 {
    case id = "page"
}
Related