How to check if an element is in an array How to check if an element is in an array arrays arrays

How to check if an element is in an array


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 inearlier releases.

Remarks:

Swift older versions:

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


For those who came here looking for a find and remove an object from an array:

Swift 1

if let index = find(itemList, item) {    itemList.removeAtIndex(index)}

Swift 2

if let index = itemList.indexOf(item) {    itemList.removeAtIndex(index)}

Swift 3, 4

if let index = itemList.index(of: item) {    itemList.remove(at: index)}

Swift 5.2

if let index = itemList.firstIndex(of: item) {    itemList.remove(at: index)}


Use this extension:

extension Array {    func contains<T where T : Equatable>(obj: T) -> Bool {        return self.filter({$0 as? T == obj}).count > 0    }}

Use as:

array.contains(1)

Updated for Swift 2/3

Note that as of Swift 3 (or even 2), the extension is no longer necessary as the global contains function has been made into a pair of extension method on Array, which allow you to do either of:

let a = [ 1, 2, 3, 4 ]a.contains(2)           // => true, only usable if Element : Equatablea.contains { $0 < 1 }   // => false