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

前端 未结 8 888
时光说笑
时光说笑 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:12

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

    func anyCommonElements(_ lhs: T, _ rhs: U) -> [T.Iterator.Element]
        where T.Iterator.Element: Equatable, T.Iterator.Element == U.Iterator.Element {
            return lhs.filter { rhs.contains($0) }
    }
    

提交回复
热议问题