Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search an Array containing struct elements in Swift?

It's kind pretty straight forward to find an element in an array with type String, Int, etc.

var States = ["CA", "FL", "MI"] var filteredStates = States.filter {$0 == "FL"} // returns false, true, false 

Now, I created a struct

struct Candy{     let name:String } 

and then initialized it

var candies =  [Candy(name: "Chocolate"), Candy(name: "Lollipop"), Candy(name: "Caramel")] 

Can anyone please suggest the right way to find "Chocolate" in the array containing struct elements? I'm not able to implement the find or filter method.

like image 552
Naren Singh Avatar asked Sep 04 '14 12:09

Naren Singh


1 Answers

With the following code you receive all candy structs in the array, which match to "Chocolate".

var candiesFiltered = candies.filter{$0.name == "Chocolate"} 

If you just want a boolean if it has been found or not you could use the following code:

var found = candies.filter{$0.name == "Chocolate"}.count > 0 
like image 71
Prine Avatar answered Sep 21 '22 01:09

Prine