Swift:在某些闭包中无法分解元组(例如,使用枚举来减少)? [英] Swift: Unable to decompose tuple in certain closures (e.g., reduce with enumerate)?

查看:87
本文介绍了Swift:在某些闭包中无法分解元组(例如,使用枚举来减少)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用map()和enumerate()时,Swift会分解枚举元组:

When using map() with enumerate(), Swift will decompose the enumerate tuple:

map(enumerate([1,2,3])) { (index, element) in
    index + element
}

但是,这似乎不能与附加的闭包参数(例如,与reduce())一起工作:

However, this does not appear to work alongside an additional closure parameter (e.g., with reduce()):

reduce(enumerate([1,2,3]), 0) { (accum, (index, element)) in
    accum + index + element
}

这会失败,并且错误:使用未声明的类型'index'

我缺少一些简单的东西,或者Swift简单地不允许分解一个元组和一个附加参数?我在1.1和1.2中尝试过。 (现在,我使用速记参数名称。)

Am I missing something simple, or does Swift simply not allow decomposing a tuple alongside an additional parameter? I have tried this in 1.1 and 1.2. (For now, I am using the shorthand argument names.)

推荐答案

答案是Swift根本不允许它。您不能像这样分解嵌套的元组。

The answer is "Swift simply not allow it". You can't decompose nested tuple like that.

例如,此代码编译,但我们不能访问 j k

For example, this code compiles, but we cannot access j or k:

func foo(i: Int, (j: Int, k: Int) ) {
    // println(j)
    //         ^ error: use of unresolved identifier 'j'
}
foo(1, (2, 3))


$ b >(j:Int,k:Int)只是一个类型,并且接收的元组本身没有名称。你必须这样写:

Because, in this code, (j: Int, k: Int) is just a type, and the received tuple itself does not have a name. You have to write like this instead:

func foo(i: Int, x: (j: Int, k: Int) ) {
    println(x.j)
}
foo(1, (1, 2))

$ b b

以同样的方式,这个编译,但它是无用的。

In the same way, this compiles, but it's useless.

reduce(enumerate([12,42,84]), 0) { (accum, (index:Int, element:Int)) in

相反,你必须接收元组本身,然后如果你想要分解它:

Instead, you have to receive the tuple itself, then decompose it if you want:

reduce(enumerate([12,42,84]), 0) { (accum, enumerated)  in
    println(enumerated.element)

    let (index, element) = enumerated

这篇关于Swift:在某些闭包中无法分解元组(例如,使用枚举来减少)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆