4

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)
}
3
  • 1
    Which object are you referring to by "the same object"? Are you wanting to check for duplicate objects? Commented Feb 19, 2015 at 19:47
  • if addPrf exist { } else {preferiti.append(addPrf)} Commented Feb 19, 2015 at 20:04
  • So you have something like this: var myArray = [1, 2, 3] and you would like to check if a number, say, 5 exists? Commented Feb 19, 2015 at 20:15

2 Answers 2

8

Swift has a generic contains function:

contains([1,2,3,4],0) -> false
contains([1,2,3,4],3) -> true
Sign up to request clarification or add additional context in comments.

2 Comments

how to use it in my case ?
@MassimilianoAllegretti Your code would say if !contains(perferiti, oggetto){ preferiti.append(addPrf) }
5

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.