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:
contains()
method requires that the sequence elements
adopt the Equatable
protocol, compare e.g. Andrews's answer.NSObject
subclass
then you have to override isEqual:
, see NSObject subclass in Swift: hash vs hashValue, isEqual vs ==.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")
}