Rapid expansion on a common structure based on type T properties

If I have a general structure, for example ...

struct Blah<T> { let someProperty: T } 

Can I then extend Blah to match Equatable only when T is Equatable . How...

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

Is it possible?

I tried several different coding methods, but each of them gives me a slightly different error.

+5
source share
1 answer

What you are looking for is

(which, in turn, is part of the "manifest manifest" ). The proposal was accepted for Swift 4, but not yet implemented. From the offer:

Conditional mappings express the idea that a generic type will conform to a particular protocol only when its type arguments satisfy certain requirements.

and a prime example is

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

make uniform arrays of equivalent elements, which is impossible at the moment. Your example essentially

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

from this sentence.

+7
source

Source: https://habr.com/ru/post/1268899/


All Articles