Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
311 views
in Technique[技术] by (71.8m points)

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

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")
        }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...