how to check if a property value exists in array of objects in swift

眉间皱痕 提交于 2019-11-28 20:06:55

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

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")
}

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")
}

A small iteration on @Antonio's solution using the , (where) notation:

if let results = objarray.filter({ $0.id == 1 }), results.count > 0 {
   print("1 exists in the array")
} else {
   print("1 does not exists in the array")
}

This works fine with me:

if(contains(objarray){ x in x.id == 1})
{
     println("1 exists in the array")
}

//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")
    }
ricardoaleixoo

signature:

let booleanValue = 'propertie' in yourArray;

example:

let yourArray= ['1', '2', '3'];

let contains = '2' in yourArray; => true
let contains = '4' in yourArray; => false

I went with this solution to similar problem. Using contains returns a Boolean value.

var myVar = "James"

if myArray.contains(myVar) {
            print("present")
        }
        else {
            print("no present")
        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!