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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With