kmkm3333 2016-02-14 14:26 采纳率: 0%
浏览 1503

Swift 2.0泛型例子解答

func anyCommonElements (lhs: T, _ rhs: U) -> Bool {
for lhsItem in lhs {
for rhsItem in rhs {
if lhsItem == rhsItem {
return true
}
}
}
return false
}
anyCommonElements([1, 2, 3], [3])

练习: 修改anyCommonElements(_:_:)函数来创建一个函数,返回一个数组,内容是两个序列的共有元素。

  • 写回答

1条回答 默认 最新

  • threenewbee 2016-02-14 21:55
    关注
     func anyCommonElements  (lhs: T, rhs: U) -> Bool { 
        for lhsItem in lhs { 
            for rhsItem in rhs { 
                if lhsItem == rhsItem { 
                    return true 
                } 
            } 
        } 
    
        return false 
    } 
    
    anyCommonElements([1, 2, 3], [3]) 
    
    func whichCommonElements  (lhs: T, rhs: U) -> Array { 
        var toReturn = Array() 
    
        for lhsItem in lhs { 
            for rhsItem in rhs { 
                if lhsItem == rhsItem { 
                    toReturn.append(lhsItem) 
                } 
            } 
        } 
    
        return toReturn 
    } 
    
    whichCommonElements([1, 2, 3], [3, 2]) 
    
    评论

报告相同问题?