Swift2 如何编写在Swift中接受CollectionType的通用递归函数?

Swift2 如何编写在Swift中接受CollectionType的通用递归函数?,swift2,Swift2,如何创建通用函数来处理Swift中的CollectionType?例如,我想要的东西可以归结为: func f<C: CollectionType>(list: C) { if list.isEmpty { return } else { f(list.dropFirst()) // causes error } } func f(列表:C){ 如果list.isEmpty{ 返回 } 否则{ f(list.dropF

如何创建通用函数来处理Swift中的CollectionType?例如,我想要的东西可以归结为:

func f<C: CollectionType>(list: C) {
    if list.isEmpty {
        return
    }
    else {
        f(list.dropFirst()) // causes error
    }
}
func f(列表:C){
如果list.isEmpty{
返回
}
否则{
f(list.dropFirst())//导致错误
}
}
这会导致错误,因为子序列可能不是CollectionType:无法使用类型为“(C.SubSequence)”的参数列表调用“f”

我尝试通过如下方式约束子序列类型来解决此问题:


不过,我也犯了同样的错误。有关如何为CollectionType编写通用递归函数的任何建议?

若要修复错误,可以使用
数组
初始值设定项将子序列转换为数组:

func f<C: CollectionType>(list: C) {
    if list.isEmpty {
        return
    }
    else {
        f(Array(list.dropFirst()))
    }
}
func f(列表:C){
如果list.isEmpty{
返回
}
否则{
f(数组(list.dropFirst())
}
}

这里有一个解决方案,它不需要在每次迭代时将存储复制到新阵列中:

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())
}
func f(c:c){
guard let first=c.first-else{return}
打印(第一)
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])
func f(c:c)其中
C:收藏,
C.子序列:收集,
C.SubSequence==C.SubSequence.SubSequence{
卫兵!c.isEmpty else{return}
f(c.dropFirst())
}
f([1,2,3])

这会在每次迭代时复制阵列。哎哟。@Alexander请发布一个更好的解决方案。:)@亚历山大:太好了,谢谢!现在让我们希望OP不接受我的答案,这样我就可以删除它。。。但考虑到它们“最后一次出现是在10月28日至15日”,这是不太可能的P没关系,希望它能帮助着陆的人