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

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

    From Swift 3, Generator protocol is renamed Iterator protocol : (link to github proposal)

    So, the function need to be written:

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

提交回复
热议问题