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

前端 未结 8 868
时光说笑
时光说笑 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条回答
  •  Happy的楠姐
    2020-12-30 00:55

    I was able to get it to work by making the return value an Array of T.GeneratorType.Element.

    func anyCommonElements  (lhs: T, rhs: U) -> Array {
        var toReturn = Array()
        for lhsItem in lhs {
            for rhsItem in rhs {
                if lhsItem == rhsItem {
                    toReturn.append(lhsItem)
                }
            }
        }
        return toReturn
    }
    anyCommonElements([1, 2, 3], [3])
    

提交回复
热议问题