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:
- This
contains()
method requires that the sequence elementsadopt theEquatable
protocol, compare e.g. Andrews's answer. - If the sequence elements are instances of a
NSObject
subclassthen you have to overrideisEqual:
, see NSObject subclass in Swift: hash vs hashValue, isEqual vs ==. - There is another – more general –
contains()
method which does not require the elements to be equatable and takes a predicate as an argument, see e.g. Shorthand to test if an object exists in an array for Swift?.
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