如何在Swift中搜索包含struct元素的Array? [英] How to search an Array containing struct elements in Swift?

查看:224
本文介绍了如何在Swift中搜索包含struct元素的Array?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在类型为String,Int等的数组中找到元素非常简单。

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
}

然后初始化它

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

任何人都可以建议正确的方法找到巧克力 在包含struct元素的数组中?我无法实现find或filter方法。

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

这篇关于如何在Swift中搜索包含struct元素的Array?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆