问题
I need to check if an array contains at least one or more elements of another array and print them out in swift. This is my situation:
var array1 = ["user1", "user2", "user3", "user4"]
var array2 = ["user3, "user5", "user7", "user9, "user4"]
//I need to get back an array that says that both the arrays contains ex. "user3" and "user4"
I searched the web but i only found the opposite answer that helps t check if there is a difference between 2 arrays using array.symmetricDifference()
Any helps??? Thanks
回答1:
You can simply create a set from your first collection and get its intersection with the other collection:
let array1 = ["user1", "user2", "user3", "user4"]
let array2 = ["user3", "user5", "user7", "user9", "user4"]
let intersection = Array(Set(array1).intersection(array2)) // ["user4", "user3"]
Note that the order of the resulting collection is unpredictable. If you would like to preserve the order of the first collection you can create a set of the second collection and filter the elements that cannot be inserted to it:
var set = Set(array2)
let intersection = array1.filter { !set.insert($0).inserted } // ["user3", "user4"]
You can also create your own intersection method on RangeReplaceableCollection:
extension RangeReplaceableCollection {
func intersection<S: Sequence>(_ sequence: S) -> Self where S.Element == Element, Element: Hashable {
var set = Set(sequence)
return filter { !set.insert($0).inserted }
}
}
Usage:
let intersection = array1.intersection(array2) // ["user3", "user4"]
来源:https://stackoverflow.com/questions/63193618/check-if-an-array-contains-elements-of-another-array-in-swift