0

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

enter image description here

Blowing my little brains

alexey.metelkin
  • 1,309
  • 1
  • 11
  • 20
  • 1
    You need to use a `Set`, not an array... – nhgrif Aug 09 '15 at 18:04
  • 1
    As in the linked-to question, you are introducing a new, local placeholder type T in the method, which is unrelated to the array element type T. Note that the possible solutions depend on the used Swift version (global function in Swift 1.2, protocol extension or restricted extension in Swift 2.0). – Martin R Aug 09 '15 at 18:05
  • @nhgrif why? but if I need this functionality on array? Order means something – alexey.metelkin Aug 09 '15 at 18:09
  • @alexey.hippie You should consider using [NSMutableOrderedSet](https://developer.apple.com/library//ios/documentation/Foundation/Reference/NSMutableOrderedSet_Class/index.html#//apple_ref/swift/cl/c:objc(cs)NSMutableOrderedSet), which will be more efficient than using an array. – Mick MacCallum Aug 09 '15 at 18:31
  • @MartinR, got your point Martin, thanks – alexey.metelkin Aug 09 '15 at 18:52
  • @0x7fffffff thanks, never use it - will check – alexey.metelkin Aug 09 '15 at 19:00

0 Answers0