How can we write to a parameter-pack tuple with the iteration syntax?

func myFunction<each T: FixedWidthInteger>(_ t: repeat each T) -> (repeat each T) {
  for value in repeat each t {
    print(value)
  }

  var result = (repeat each t)
  for dummy in repeat each ??? {  // `result`, or `&result`, is in the ???
    dummy += 1
  }
  return result
}

How can I write to each member of result one at a time? (I can't use an all-at-once functional solution here.) The actual needs are more complicated, but I need to work with the above first before asking new questions.

1 Like

I think for now you're limited to an all-at-once functional solution.

It's not obvious from documentation, but you can call function on each element. In example below, I map simple { $0 + 1 } closure on each member of tuple.

Maybe something like this could meet your needs.

func myFunction<each T: FixedWidthInteger>(_ t: repeat each T) -> (repeat each T) {

    return (repeat { $0 + 1 }(each t) )
}

// Prints:
//   (2, 3, 4, 5)
let result = myFunction(1, 2, 3, 4)
print(result)
2 Likes

Unfortunately we don't have a way to actually mutate or initialize packs like that yet.

You can always use the "functional solution" actually, if you extract the body of your for loop into a local function foo() that returns the new value, and then you can do var result = (repeat foo(each t)) to form the result.