在关闭中破坏元组的元组 [英] Destructuring tuple of tuple in closure
本文介绍了在关闭中破坏元组的元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以很容易地破坏一个元组的元组:
I can destructure a tuple of tuple easily:
let tt = (2, (3, 4))
let (a, (b, c)) = tt
b // => 3
我想在声明关闭时做同样的事情,例如,我以为我可以写:
I'd like to do the same when declaring a closure, for example I thought I could write:
[tt].map { (a, (b, c)) in
// Use b
}
Xcode抱怨未命名参数必须用空名称写。
Xcode complains with "Unnamed parameters must be written with the empty name".
让我工作的唯一方法是:
Only way I got it to "work" was:
[tt].map { (a, tuple: (b: Int, c: Int)) in
// Use tuple.b
}
我想避免两个缺点:
- 我需要使用
tuple.b
代替b
- 我需要指定类型
b
和c
- I need to use
tuple.b
instead ofb
- I need to specify the types of
b
andc
顺便说一句,我的用例是我想对索引进行 reduce
,所以我尝试使用 array.enumerate()。reduce
BTW, my use case is that I want to do a reduce
with index so I'm trying using array.enumerate().reduce
推荐答案
使用附加的赋值行,可以将数组中的值赋给(a ,(b,c))
解构元组:
With an additional assignment line, you can assign the values in the array to (a, (b, c))
to deconstruct the tuple:
let tt1 = (2, (3, 4))
let tt2 = (5, (6, 7))
[tt1, tt2].map { tt in
let (a, (b, c)) = tt
print(b)
}
输出:
3
6
或者:
Alternatively:
[tt1, tt2].map {
let (a, (b, c)) = $0
print(b)
}
这篇关于在关闭中破坏元组的元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文