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

前端 未结 8 795
时光说笑
时光说笑 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 01:09

    The accepted answer is no longer valid for the latest version of Swift. Here is an update that is compatible with version 3.0.1, they have simplified how to make a generic array.

    func showCommonElements<T: Sequence, U: Sequence>(_ lhs: T, _ rhs: U) -> [T.Iterator.Element]
        where T.Iterator.Element: Equatable, T.Iterator.Element == U.Iterator.Element {
            var result:[T.Iterator.Element] = []
            for lhsItem in lhs {
                for rhsItem in rhs {
                    if lhsItem == rhsItem {
                        result.append(lhsItem)
                    }
                }
            }
            return result
    }
    

    You can test the code with the following commands:

    showCommonElements([1, 2, 3, 4, 5], [4, 7, 3])
    showCommonElements(["apple", "banana", "orange", "peach"], ["orange", "pear", "apple"])
    
    0 讨论(0)
  • 2020-12-30 01:12

    The cleanest way to solve this in Swift 3 is using the filter function as follows:

    func anyCommonElements<T: Sequence, U: Sequence>(_ lhs: T, _ rhs: U) -> [T.Iterator.Element]
        where T.Iterator.Element: Equatable, T.Iterator.Element == U.Iterator.Element {
            return lhs.filter { rhs.contains($0) }
    }
    
    0 讨论(0)
提交回复
热议问题