how to check if a property value exists in array of objects in swift
You can filter the array like this:
let results = objarray.filter { $0.id == 1 }
that will return an array of elements matching the condition specified in the closure - in the above case, it will return an array containing all elements having the id
property equal to 1.
Since you need a boolean result, just do a check like:
let exists = results.isEmpty == false
exists
will be true if the filtered array has at least one element
//Swift 4.2
if objarray.contains(where: { $0.id == 1 }) {
// print("1 exists in the array")
} else {
// print("1 does not exists in the array")
}
In Swift 2.x:
if objarray.contains({ name in name.id == 1 }) {
print("1 exists in the array")
} else {
print("1 does not exists in the array")
}
In Swift 3:
if objarray.contains(where: { name in name.id == 1 }) {
print("1 exists in the array")
} else {
print("1 does not exists in the array")
}