1

I have a viewController that has a variable and it's getting the value of this variable from another view controller so the variable is like this for example..

var name = "Step-Up to Emergency Medicine"

and there is a button when clicked it's append this string to an arraylist

@IBAction func add(_ sender: Any) {
        myArray.append(name)
}

my question is how to prevent the arraylist from adding the same string value twice?

0

1 Answer 1

1

Make sure the string isn't already in the array before appending, like this:

@IBAction func add(_ sender: Any) {
   if !myArray.contains(name) {
       myArray.append(name)
   }
}
1
  • Better to use a set but if your list contains just a few elements you won't notice any difference.
    – Leo Dabus
    Commented May 8, 2021 at 21:18

Not the answer you're looking for? Browse other questions tagged or ask your own question.