Check if an array contains elements of another array in swift

前端 未结 1 672
暗喜
暗喜 2021-01-27 04:45

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&q         


        
相关标签:
1条回答
  • 2021-01-27 05:21

    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"]
    
    0 讨论(0)
提交回复
热议问题