问题描述
- 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(_:_:)函数来创建一个函数,返回一个数组,内容是两个序列的共有元素。
解决方案
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])
时间: 2024-09-27 20:16:10