Swift 3过滤对象数组和数组元素 [英] Swift 3 filter array of objects with elements of array
本文介绍了Swift 3过滤对象数组和数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
array1 = array1.filter{ $0.arrayInsideOfArray1.contains(array2[0]) }
上面的代码有效,但是我试图检查$ 0.arrayInsideOfArray1的所有元素是否与array2的所有元素匹配,而不仅仅是[0]
Code above works but I'm trying to check if all the elements of $0.arrayInsideOfArray1 match with all the elements of array2 not just [0]
示例:
struct User {
var name: String!
var age: Int!
var hasPet: Bool!
var pets: [String]!
}
var users: [User] = []
users.append(User(name: "testUset", age: 43, hasPet: true, pets: ["cat", "dog", "rabbit"]))
users.append(User(name: "testUset1", age: 36, hasPet: true, pets:["rabbit"]))
users.append(User(name: "testUset2", age: 65, hasPet: true, pets:["Guinea pigs", "Rats"]))
let petArr = ["cat", "dog", "rabbit"]
users = users.filter { $0.pets.contains(petArr[0]) }
我想要的是在petArr中列出任何宠物的任何用户!
What I want is any user that has any pet listed in the petArr!
推荐答案
一种方法是更新过滤器,以查看pets中是否有任何值位于petArr
数组中:
One approach is to update your filter to see if any value in pets is in the petArr
array:
users = users.filter { $0.pets.contains(where: { petArr.contains($0) }) }
第一个$0
来自filter
,它代表每个User
.
The first $0
is from the filter
and it represents each User
.
第二个$0
来自第一个contains
,它表示当前User
的pets
数组中的每个宠物.
The second $0
is from the first contains
and it represents each pet within the pets
array of the current User
.
这篇关于Swift 3过滤对象数组和数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文