How to search an Array containing struct elements in Swift?

拥有回忆 提交于 2019-12-18 12:10:58

问题


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:


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


来源:https://stackoverflow.com/questions/25665122/how-to-search-an-array-containing-struct-elements-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!