我正在尝试完成苹果新书“Swift编程语言”第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,T.GeneratorType.Element: Equatable,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,[3])
但在第2行,我收到错误:找不到成员’下标’
通过使返回值为T.GeneratorType.Element的数组,我可以使其工作。
原文链接:https://www.f2er.com/swift/320510.htmlfunc anyCommonElements <T,U where T: SequenceType,U: SequenceType,T.Generator.Element: Equatable,T.Generator.Element == U.Generator.Element> (lhs: T,rhs: U) -> Array<T.Generator.Element> { var toReturn = Array<T.Generator.Element>() for lhsItem in lhs { for rhsItem in rhs { if lhsItem == rhsItem { toReturn.append(lhsItem) } } } return toReturn } anyCommonElements([1,[3])