Use a function to find common elements in two sequences in Swift

前端 未结 8 797
时光说笑
时光说笑 2020-12-30 00:07

I\'m trying to complete the exercise on page 46 of Apple\'s new book \"The Swift Programming Language\". It gives the following code:

func anyCommonElements         


        
8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-30 00:51

    Although this question has been answered, and the original question was about working with generic arrays, there is a way using Set and improving the stackoverflow knowledge base I still want to post it.

    The swift class Set contains these four methods:

    Set.union(sequence:)
    Set.subtract(sequence:)
    Set.intersect(sequence:)
    Set.exclusiveOr(sequence:)
    

    which are documented here: https://developer.apple.com/library/ios/documentation/Swift/Reference/Swift_Set_Structure/index.html

    You can convert two arrays into sets and use these methods:

    let array1 = [1, 2, 3]
    let array2 = [3, 4]
    
    let set1 = Set(array1)
    let set2 = Set(array2)
    
    let union = set1.union(set2)                // [2, 3, 1, 4]
    let subtract = set1.subtract(set2)          // [2, 1]
    let intersect = set1.intersect(set2)        // [3]
    let exclusiveOr = set1.exclusiveOr(set2)    // [2, 4, 1]
    

    Edit 1:

    Like Martin R mentioned in a comment, the type of Set has to inherit the protocol Hashable, which is slightly more restrictive than Equatable. And also the order of elements is not preserved, therefore consider the relevance of ordered elements!

提交回复
热议问题