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 qu
Use this extension:
extension Array {
func contains(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 : Equatable
a.contains { $0 < 1 } // => false