Swift extension on generic struct based on properties of type T

后端 未结 1 797
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-20 15:48

If I have a generic struct like...

struct Blah {
    let someProperty: T
}

Can I then extend Blah to conform to

1条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-20 16:48

    Update: Conditional conformance has been implemented in Swift 4.1, and your code

    struct Blah {
        let someProperty: T
    }
    
    extension Blah: Equatable where T: Equatable {
        static func == (lhs: Blah, rhs: Blah) -> Bool {
            return lhs.someProperty == rhs.someProperty
        }
    }
    

    compiles and works as expected in Xcode 9.3.


    What you are looking for is

    • SE-0143 Conditional conformances

    (which in turn is part of the "Generics Manifesto"). The proposal has been accepted for Swift 4 but not yet implemented. From the proposal:

    Conditional conformances express the notion that a generic type will conform to a particular protocol only when its type arguments meet certain requirements.

    and a prominent example is

    extension Array: Equatable where Element: Equatable {
      static func ==(lhs: Array, rhs: Array) -> Bool { ... }
    }
    

    to make arrays of equatable elements equatable, which is not possible at present. Your example is essentially

    struct SomeWrapper {
      let wrapped: Wrapped
    }
    
    extension SomeWrapper: Equatable where Wrapped: Equatable {
      static func ==(lhs: SomeWrapper, rhs: SomeWrapper) -> Bool {
        return lhs.wrapped == rhs.wrapped
      }
    }
    

    from that proposal.

    0 讨论(0)
提交回复
热议问题