Search code examples
arraysswiftnsarray

Check if an array already contains a string value in Swift


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.


Solution

  • 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.