Search code examples
swiftprotocolsswift-protocolsswift-extensions

How to fix `Implementation of 'Protocol' cannot be automatically synthesized in an extension`?


I'm getting a compiler error while adding new protocol conformance to an extension.

struct EquatableStruct { }

extension EquatableStruct: Equatable {
  static func == (lhs: EquatableStruct, rhs: EquatableStruct) -> Bool {
    return true
  }
}

Here I'm getting the compiler error:

Implementation of 'Equatable' cannot be automatically synthesized in an extension

How do I fix this issue?


Solution

  • You are misquoting the error. It should be:

    Implementation of 'Equatable' cannot be automatically synthesized in an extension

    Comparable extends Equatable. If you want your extension to conform to Comparable you must also implement the Equatable protocol.

    extension ComparableStruct: Comparable {
        static func < (lhs: ComparableStruct, rhs: ComparableStruct) -> Bool {
            return true // FIX
        }
    
        static func == (lhs: ComparableStruct, rhs: ComparableStruct) -> Bool {
            return true // FIX
        }
    }