Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extend protocol Optional, where Wrapped item is Array of Equatable generic elements?

I would say this problem is about proper declaration of extension.

I would like to extend Array filled with generic Elements, where Element conforms to Equatable. I've managed to do that by :

    extension Array where Element: Equatable{
        // my code
    }

However I'd like to know how to properly declare extension when the Array filled with Equatable elements is inside an Optional? I know that in this case I am actually extending protocol Optional, but I can't figure out the rest

I was thinking something like:

    extension Optional where Wrapped: Array  & Equatable {
      // my code
    }

Can't figure it out. Any ideas ?

like image 447
Peter Ševčík Avatar asked Dec 14 '22 13:12

Peter Ševčík


1 Answers

Cristik provided a good solution. An alternative is to write an extension to an optional collection of equatable elements:

extension Optional where Wrapped: Collection, Wrapped.Element: Equatable {
    func foo() { }
}

This would be applicable to arrays, array slices, and other collections.

Depending on what the extension does, you may want to use a combination of Collection, MutableCollection, BidirectionalCollection, RandomAccessCollection.

like image 180
Martin R Avatar answered Jan 13 '23 13:01

Martin R