Reputation: 8737
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)
Upvotes: 1
Views: 1648
Reputation: 236350
You are already constraining the collection elements to equatable, so there is no need to create a new generic equatable type at your method:
extension RangeReplaceableCollection where Element: Equatable {
mutating func appendIfNotContains(_ element: Element) {
if !contains(element) { append(element) }
}
}
Upvotes: 4