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)
append
doesn't exist onMutableCollection
because not all mutable collections support arbitrary sizes likeArray
does. Make this as an extension onArray
.NSOrderedSet
(which I guess is called anOrderedSet
in Swift 3)