How to check if an element is in an array

jaredsmith picture jaredsmith · Jun 8, 2014 · Viewed 416.5k times · Source

In Swift, how can I check if an element exists in an array? Xcode does not have any suggestions for contain, include, or has, and a quick search through the book turned up nothing. Any idea how to check for this? I know that there is a method find that returns the index number, but is there a method that returns a boolean like ruby's #include??

Example of what I need:

var elements = [1,2,3,4,5]
if elements.contains(5) {
  //do something
}

Answer

Martin R picture Martin R · Aug 19, 2014

Swift 2, 3, 4, 5:

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

contains() is a protocol extension method of SequenceType (for sequences of Equatable elements) and not a global method as in earlier releases.

Remarks:

Swift older versions:

let elements = [1,2,3,4,5]
if contains(elements, 5) {
    println("yes")
}