1

I have an Array that is declared as:

var stringsArray: Array<String!> = []

I want to add items to it using code along these lines:

stringsArray.append("String 1")

However, I would like to use an if statement to detect whether or not what is about to be appended already exists in stringsArray and if it does, I would like the code to append not to be ran.

I am using Swift.

Daniel Bramhall
  • 1,451
  • 4
  • 18
  • 24

1 Answers1

3

You can simply use this:

var elements = [1,2,3,4,5]
if contains(elements, 5) {
    print("Array contains 3")
}

For Swift 2.2 and later, there is a member contains():

var elements = [1, 2, 3, 4, 5]
if elements.contains(3) {
    print("Array contains 3")
}

Resource: How to check if an element is in an array.

Community
  • 1
  • 1
Altay Mazlum
  • 442
  • 5
  • 15