let toBeFiltered = ["star0", "star2", "star1", "star0", "star3", "star4"]
let theFilter = ["star1", "star3"]
let filtered = Set(toBeFiltered).intersect(theFilter)
// => ["star1", "star3"] of type Set<String>
// ...if you actually need an array, you can get one using Array(filtered)
//: Playground - noun: a place where people can play
import Foundation
extension Collection where Element: Equatable {
func intersection(with filter: [Element]) -> [Element] {
return self.filter { element in filter.contains(element) }
}
}
let toBeFiltered = ["star0", "star2", "star1", "star0", "star3", "star4", "star1"]
let theFilter = ["star1", "star3"]
let filtered = toBeFiltered.intersection(with: theFilter) // ["star1", "star3", "star1"]
6条答案
按热度按时间a14dhokn1#
使用集合操作
阅读更多信息:https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html
5ssjco0h2#
zfycwa2u3#
您也可以筛选Struct数组
对于Set,您必须符合哈希协议
kb5ga3dv4#
这似乎是今天的主题:)基于另一个很好的答案,我建议在
Set
上使用intersect(_:)
方法:omtl5h9j5#
j2cgzkjk6#
虽然使用Arsen建议的Sets无疑是最优雅的,但有时您希望保留副本和顺序: