Swift51.com
bigcake 头像
bigcake  2018-04-16 18:21

菜鸟提问

回复:2  查看:4419  
能否定义一个方法,比较两个数组的值。
若数组内值的类型相同,返回一个包含两个数组相同的值的数组。
若数组内值的类型不相同,则抛出一个错误。
ps:在阅读泛型篇章时想到的问题,但写不出实现这个方法的代码,在此请教!
Swift 头像
Swift  2018-04-18 10:23
这里有个类似的代码
func anyCommonElements<T: Sequence, U: Sequence>(_ lhs: T, _ rhs: U) -> Bool
    where T.Iterator.Element: Equatable, T.Iterator.Element == U.Iterator.Element {
        for lhsItem in lhs {
            for rhsItem in rhs {
                if lhsItem == rhsItem {
                    return true
                }
            }
        }
        return false
}
anyCommonElements([1, 2, 3], [3])
这个帖子里摘出来的
大头大哥orz 头像
大头大哥orz  2018-04-18 10:55
func anyCommonElements<T: Sequence, U: Sequence>(_ lhs: T, _ rhs: U) -> T
    where T.Iterator.Element: Equatable, T.Iterator.Element == U.Iterator.Element {
        var temp = T()
        for lhsItem in lhs {
            for rhsItem in rhs {
                if lhsItem == rhsItem {
                    temp.appand(lhsItem)
                }
            }
        }
        return temp
}
anyCommonElements([1, 2, 3], [3])