34

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.

1 Answer 1

46

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
Sign up to request clarification or add additional context in comments.

3 Comments

The syntax can be simplified as filter { $0.name == ... } since the closure is 'trailing'.
Is it possible to also filter with a dynamic string? something like: var candiesFiltered = candies.filter{$0[customProperty] == "Chocolate"}
can we use to || operator inside the filter block? I need to compare fromString & toString

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.