如何快速检查对象数组中是否存在属性值 [英] how to check if a property value exists in array of objects in swift

查看:253
本文介绍了如何快速检查对象数组中是否存在属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检查对象数组中是否存在特定项目(属性的值),但是找不到任何解决方案。请让我知道,我在这里缺少什么。

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


推荐答案

您可以像这样过滤数组:

You can filter the array like this:

let results = objarray.filter { $0.id == 1 }

将返回匹配闭包中指定条件的元素数组-在上述情况下,它将返回一个包含所有具有 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

这篇关于如何快速检查对象数组中是否存在属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆