Błażej
Błażej

Reputation: 3635

Swift Array extension with optionals

I've created simple extension for Array which will append only unique elements. It works fine until I want to work with an array of optionals. Since that I'm keep getting error Type 'Event?' does not conform to protocol 'Equatable'

Event class

import RealmSwift
class Event: Object,Equatable {
    dynamic var id = ""
}

func ==(lhs: Event, rhs: Event) -> Bool {
    return lhs.id == rhs.id
}

Extension

extension Array where Element : Equatable {
    mutating func appendUniqueContentOf(elements:[Element]){
        for ele in elements {
            if (!contains(ele)){
                append(ele)
            }
        }
    }
}

Usage

var newEvents:[Event] = someEvents()
var events = [Event?]()
events.appendUniqueContentOf(newEvents)

Question I don't understand this situation. Event class conform that protocol. I've also tried adding other combination of == function, but without success.

I don't know how to approah this issue. Is it matter of my extension? How I should properly approach it? Could you show me right track?

Upvotes: 1

Views: 777

Answers (1)

Vatsal
Vatsal

Reputation: 18181

Event? is syntactic sugar for Optional<Event>. Since Optional does not conform to Equatable, neither will Optional<Event>.

Though possible, I highly discourage implementing Equatable for Optional. This being said, you should probably rethink and try using just Array<Event>.

Upvotes: 1

Related Questions