使用泛型创建一个函数,在Swift中返回另一个函数

时间:2014-06-06 04:38:19

标签: swift nested-function

我的问题是基于Swift的书的导览章,其中给出了以下代码:

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 myCommonElements<T, U where T: Sequence, U: Sequence,
    T.GeneratorType.Element: Equatable,
    T.GeneratorType.Element == U.GeneratorType.Element>
    (lhs: T) -> (U -> Array<U.GeneratorType.Element>)
{
    func makeCommon (rhs: U) -> Array<U.GeneratorType.Element>
    {
        var commonArray = Array<U.GeneratorType.Element>()
        for lhsItem in lhs {
            for rhsItem in rhs {
                if lhsItem == rhsItem {
                    commonArray.append(lhsItem)
                }
            }
        }
        return commonArray
    }
    return makeCommon
}

let gatherCommon = myCommonElements([3, 4, 5, 6])
let result = gatherCommon([1, 2, 3, 4])
println(result)

我得到的错误是:

cannot convert the expression's type 
'(rhs: $T2 -> Array<$T4>)' to type 'Generator'

我理解错误,但我不确定为什么我收到此错误。我做错了什么?

1 个答案:

答案 0 :(得分:3)

当你调用myCommonElements时,你将类型T作为参数传递。编译器如何推断U的类型?声明返回类型,你会没事的。

let gc: Array<Int> -> Array<Int> = myCommonElements([3,4,5,6])
相关问题