Trying to make swift array extension that add object to array only if array not already contain it, i.e prevent duplicates
Here is a function
func contains<T : Equatable>(obj: T) -> Bool {
let filtered = self.filter {$0 as? T == obj}
return filtered.count > 0
}
mutating func appendOnce<T : Equatable>(newElement: T) -> Bool {
// append object only if there is no same object in array
// return true if added
var result = false
if self.contains(newElement) {
self.append(newElement)
result = true
}
return result
}
But if I set appendOnce with then compiler says:
Cannot invoke 'append' with an argument list of type '(T)'
Why? append method takes newObject of T type, newObject is T type
Blowing my little brains