Reputation: 199
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)
}
Upvotes: 4
Views: 13933
Reputation: 1792
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.
Upvotes: 5
Reputation: 6657
Swift has a generic contains
function:
contains([1,2,3,4],0) -> false
contains([1,2,3,4],3) -> true
Upvotes: 8