[英]Swift filter an array inside a struct by another array
我有一個 Profile 數組(從自定義結構定義),在其中,我有一個感興趣的 [String]。
我想過濾掉與一系列偏好不匹配的任何配置文件,但似乎無法讓我的過濾工作。
我得到的錯誤是
“無法將 '[String]' 類型的值轉換為預期的參數類型 'String'。
我錯過了什么?
完成后,我希望userProfiles
只包含 John 和 Harry。
struct Profile {
var name: String
var interests: [String]
}
var userProfiles: [Profile] = [
Profile(name: "John", interests: ["Basketball", "Football", "Rowing"]),
Profile(name: "Andrew", interests: ["Cycling", "Swimming", "Boxing"]),
Profile(name: "Harry", interests: ["Hockey", "Baseball"])
]
let preferenceInterests = ["Basketball", "Hockey"]
userProfiles = userProfiles.filter({ (userProfile) -> Bool in
print("\(userProfile.name): \(userProfile.interests)")
return preferenceInterests.contains(userProfile.interests) //error here
})
您的問題是userProfile.interests
是一個數組,因此它不是包含String
的preferencesInterests
元素。
如果你仔細想想,你就是在嘗試看看兩組興趣是否有共同點。 這是Set
交點。 為此, Sets
比數組更有效,因為檢查包含是 O(1) 而不是 O(n)。
通過將preferenceIntests
設置為Set<String>
您可以使用.isDisjoint(with:)
來查看是否有任何共同興趣。 一旦 Swift 找到一個共同的興趣點,它就會返回false
,因為這些集合包含一個共同的元素並且不是不相交的。 您需要反轉它,因為您希望共同利益返回true
:
let preferenceInterests: Set = ["Basketball", "Hockey"]
userProfiles = userProfiles.filter({ (userProfile) -> Bool in
print("\(userProfile.name): \(userProfile.interests)")
return !preferenceInterests.isDisjoint(with: userProfile.interests)
})
問題是userProfile.interests
本身就是一個數組。 根據您的示例和 John 和 Harry 的預期輸出,您實際上想要實現的似乎是保留與您的preferenceInterests
輸入相比具有至少 1 個匹配興趣的用戶。
為此,您需要更改filter
的主體並使用contains(where:)
而不是contains
來檢查是否有興趣匹配。
let filteredUsers = userProfiles.filter { userProfile in
preferenceInterests.contains(where: { interest in userProfile.interests.contains(interest) })
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.