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

前端 未结 8 793
时光说笑
时光说笑 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(_ 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"])
    

提交回复
热议问题