Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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")         } 
like image 287
Nuibb Avatar asked Jan 29 '15 09:01

Nuibb


People also ask

How do you check a value contains in an array in Swift?

It's easy to find out whether an array contains a specific value, because Swift has a contains() method that returns true or false depending on whether that item is found. For example: let array = ["Apples", "Peaches", "Plums"] if array.

Which property that used to check an array has items in Swift?

Use the isEmpty property to check quickly whether an array has any elements, or use the count property to find the number of elements in the array.

How do you check if an object exists in Swift?

To check if an element is in an array in Swift, use the Array. contains() function.

How do you check if an element belongs to an array?

The simplest and fastest way to check if an item is present in an array is by using the Array. indexOf() method. This method searches the array for the given item and returns its index. If no item is found, it returns -1.


2 Answers

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

like image 125
Antonio Avatar answered Sep 20 '22 19:09

Antonio


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") } 
like image 20
TheEye Avatar answered Sep 19 '22 19:09

TheEye