how to check if a property value exists in array o

2019-01-22 17:42发布

I am trying to check if a specific item (value of a property) exists in a array of objects, but could not find out any solution. Please let me know, what i am missing here.

        class Name {
            var id : Int
            var name : String
            init(id:Int, name:String){
                self.id = id
                self.name = name
            }
        }

        var objarray = [Name]()
        objarray.append(Name(id: 1, name: "Nuibb"))
        objarray.append(Name(id: 2, name: "Smith"))
        objarray.append(Name(id: 3, name: "Pollock"))
        objarray.append(Name(id: 4, name: "James"))
        objarray.append(Name(id: 5, name: "Farni"))
        objarray.append(Name(id: 6, name: "Kuni"))

        if contains(objarray["id"], 1) {
            println("1 exists in the array")
        }else{
            println("1 does not exists in the array")
        }

7条回答
Root(大扎)
2楼-- · 2019-01-22 18:13

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")
}
查看更多
贼婆χ
3楼-- · 2019-01-22 18:13

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")
        }
查看更多
forever°为你锁心
4楼-- · 2019-01-22 18:18

This works fine with me:

if(contains(objarray){ x in x.id == 1})
{
     println("1 exists in the array")
}
查看更多
ら.Afraid
5楼-- · 2019-01-22 18:30

signature:

let booleanValue = 'propertie' in yourArray;

example:

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

let contains = '2' in yourArray; => true
let contains = '4' in yourArray; => false
查看更多
再贱就再见
6楼-- · 2019-01-22 18:32

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

查看更多
Emotional °昔
7楼-- · 2019-01-22 18:34

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")
}
查看更多
登录 后发表回答