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
let elements = [1, 2, 3, 4, 5, 5]
elements.contains(5) // true
elements.firstIndex(of: 5) // 4
elements.firstIndex(of: 10) // nil
let results = elements.filter { element in element == 5 }
results.count // 2
if user find particular array elements then use below code same as integer value.
var arrelemnts = ["sachin", "test", "test1", "test3"]
if arrelemnts.contains("test"){
print("found") }else{
print("not found") }
The simplest way to accomplish this is to use filter on the array.
let result = elements.filter { $0==5 }
result
will have the found element if it exists and will be empty if the element does not exist. So simply checking if result
is empty will tell you whether the element exists in the array. I would use the following:
if result.isEmpty {
// element does not exist in array
} else {
// element exists
}
As of Swift 2.1 NSArrays have containsObject
that can be used like so:
if myArray.containsObject(objectImCheckingFor){
//myArray has the objectImCheckingFor
}
Swift 4.2 +
You can easily verify your instance is an array or not by the following function.
func verifyIsObjectOfAnArray<T>(_ object: T) -> Bool {
if let _ = object as? [T] {
return true
}
return false
}
Even you can access it as follows. You will receive nil
if the object wouldn't be an array.
func verifyIsObjectOfAnArray<T>(_ object: T) -> [T]? {
if let array = object as? [T] {
return array
}
return nil
}