【发布时间】:2014-06-04 00:47:13
【问题描述】:
我正在尝试完成 Apple 新书“The Swift Programming Language”第 46 页的练习。它给出了以下代码:
func anyCommonElements <T, U where T: Sequence, U: Sequence, T.GeneratorType.Element: Equatable, T.GeneratorType.Element == U.GeneratorType.Element> (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 anyCommonElements <T, U where T: Sequence, U: Sequence, T.GeneratorType.Element: Equatable, T.GeneratorType.Element == U.GeneratorType.Element> (lhs: T, rhs: U) -> T.GeneratorType[] {
var toReturn = T.GeneratorType[]()
for lhsItem in lhs {
for rhsItem in rhs {
if lhsItem == rhsItem {
toReturn.append(lhsItem)
}
}
}
return toReturn
}
anyCommonElements([1, 2, 3], [3])
但在第 2 行,我收到错误:找不到成员“下标”
此错误的原因是什么?解决此问题的最佳方法是什么?
【问题讨论】:
标签: swift