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条回答
2楼-- · 2019-01-22 18:34

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