简体   繁体   English

如何在Swift中搜索包含struct元素的Array?

[英]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. 在类型为String,Int等的数组中查找元素非常简单。

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? 任何人都可以建议在包含struct元素的数组中找到“Chocolate”的正确方法吗? I'm not able to implement the find or filter method. 我无法实现find或filter方法。

With the following code you receive all candy structs in the array, which match to "Chocolate" . 使用以下代码,您将收到数组中所有与"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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM