RawMean RawMean - 16 days ago 10
iOS Question

Swiftt3: Extension to append to Array if not duplicate

I'm trying to write an extension to Array that appends an element to the Array only if the element does not exists in the Array already.

This is my code:

extension MutableCollection where Iterator.Element: Equatable {
mutating func addObjectIfNew <T: Equatable> (_ item: T) {
if !self.contains(item as! Self.Iterator.Element) {
self.append(x as! Self.Iterator.Element) // offending line
}
}
}


I get this error:


error: value of type 'Self' has no member 'append'


What's the proper way to write such extension?

Update: I can't use a Set because I need to perform this operation on an object that needs to be indexed (i.e., Array)

Answer

You are already constraining the collection type to equatable, so there is no need to use T: Equatable at your method. You can do it as follow:

extension Array where Element: Equatable {
    mutating func addObjectIfNew(_ item: Element) { 
        if !contains(item) {
            append(item) 
        }
    }
}