如何编写一个在Swift中采用CollectionType的通用递归函数?

时间:2015-10-26 14:30:42

标签: swift2

如何在Swift中创建一个处理CollectionType的泛型函数?例如,我想要的东西归结为:

func f<C: CollectionType>(list: C) {
    if list.isEmpty {
        return
    }
    else {
        f(list.dropFirst()) // causes error
    }
}

这会导致错误,因为SubSequence可能不是CollectionType:无法使用类型为'(C.SubSequence)'的参数列表调用'f'

我尝试通过约束SubSequence类型来解决它:

<C: CollectionType where C.SubSequence: CollectionType>

但是,我得到了同样的错误。有关如何为CollectionType编写通用递归函数的任何建议吗?

2 个答案:

答案 0 :(得分:0)

要修复错误,您可以使用Array初始化程序将SubSequence转换为数组:

func f<C: CollectionType>(list: C) {
    if list.isEmpty {
        return
    }
    else {
        f(Array(list.dropFirst()))
    }
}

答案 1 :(得分:0)

这是一个解决方案,无需每次迭代都需要在新数组中复制存储:

func f<C: CollectionType
    where C.SubSequence: CollectionType,
    C.SubSequence == C.SubSequence.SubSequence>(c: C) {

    guard let first = c.first else { return }

    print(first)
    f(c.dropFirst())
}

在Swift 3中:

func f<C>(_ c: C) where 
    C: Collection,
    C.SubSequence: Collection,
    C.SubSequence == C.SubSequence.SubSequence {

    guard !c.isEmpty else { return }
    f(c.dropFirst())
}

f([1, 2, 3])