Destroying a tuple in a closure tuple

I can easily destroy a tuple of a tuple:

let tt = (2, (3, 4)) let (a, (b, c)) = tt b // => 3 

I would like to do the same when declaring closure, for example, I thought I could write:

 [tt].map { (a, (b, c)) in // Use b } 

Xcode complains about "An unnamed parameter must be written with an empty name."

The only way to make it β€œwork” was:

 [tt].map { (a, tuple: (b: Int, c: Int)) in // Use tuple.b } 

This has two drawbacks that I would like to avoid:

  • I need to use tuple.b instead of b
  • I need to specify types b and c

By the way, my use case is I want to do reduce with an index, so I'm trying to use array.enumerate().reduce

+6
source share
3 answers

With an additional destination string, you can assign values ​​in the array (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) } 

Output:

 3 6 

As an alternative:

 [tt1, tt2].map { let (a, (b, c)) = $0 print(b) } 
+2
source

This satisfies your first requirement, but still requires you to add an annotation like:

 typealias TupleType = (a: Int, tuple: (b: Int, c: Int)) let tt: TupleType = (2, (3, 4)) [tt].map { print($0.tuple.b) } 
+1
source

Another workaround:

 [tt].map { a, b in let (b, c) = b print(a, b, c) } 
0
source

All Articles