Xcode Swift check if array contains object

arrays, swift

Solution

So it sounds like you want an array without duplicate objects. In cases like this, a `set` is what you want. Surprisingly, Swift doesn't have a set, so you can either create your own or use `NSSet`, which would look something like this:

let myset = NSMutableSet()
myset.addObject("a") // ["a"]
myset.addObject("b") // ["a", "b"]
myset.addObject("c") // ["a", "b", "c"]
myset.addObject("a") // ["a", "b", "c"] NOTE: this doesn't do anything because "a" is already in the set.

UPDATE:

Swift 1.2 added a set type! Now you can do something like

let mySet = Set<String>()
mySet.insert("a") // ["a"]
mySet.insert("b") // ["a", "b"]
mySet.insert("c") // ["a", "b", "c"]
mySet.insert("a") // ["a", "b", "c"] NOTE: this doesn't do anything because "a" is already in the set.

Problem

I have this array : ``` var preferiti : [ModalHomeLine!] = [] ``` I want to check if the array contains the same object. ``` if the object exists { } else { var addPrf = ModalHomeLine(titolo: nomeLinea, link: linkNumeroLinea, immagine : immagine, numero : titoloLinea) preferiti.append(addPrf) } ```

Original source