Type 'SkillLevel' does not conform to protocol 'Comparable'

Just going through the "Adopting a Protocol Using a Synthesized Implementation" section of the the swift programming language.

When the following enum code is run, the following error is displayed in Xcode (project, playground or repl/CLI):

enum SkillLevel: Comparable {
    case beginner
    case intermediate
    case expert(stars: Int)
Type 'SkillLevel' does not conform to protocol 'Comparable'

According to the text above this code it should conform automatically. Although intuitively, since SkillLevel is a custom type, it is not obvious how the compiler would know how the cases compare.

What am I missing here?

It was added in Swift 5.3 (SE-0266 Synthesized Comparable conformance for enum types), so it's not yet available.

Ok. :cool:. So, how does it compare without something obvious to compare?

You mean the (upcoming) synthesised comparator? From the linked proposal:

[enums with associated values] will compare by case declaration order first, and then lexicographically by payload values.


Thank you, Lantua. I've just read the proposal and found the bit I was after. Very :cool:.

Comparable conformance would compare according to case declaration order, with later cases comparing greater than earlier cases.

Does this conformance require all associated values to also conform to Comparable? Otherwise, how would it perform the secondary comparison for payload after the initial comparison by case?

The proposal states the following regarding associated values.

Only enum types with no associated values and enum types with only Comparable associated values would be eligible for synthesized conformances.

Note: The SkillLevel enum works fine in Xcode 12 beta 6 :nerd_face:

1 Like
Terms of Service

Privacy Policy

Cookie Policy