How can we get the last member of a tuple?

We can use "myTuple.0" to get the first member of a tuple. Is there a similar way for the last member? The members are static numbers (AIUI), so "myTuple.(count - 1)" can't work.

I'm interested because of variadic generics. We can use a function family to peel off the front members, but that's inherently O(n), and I prefer something O(1). Hopefully, we only need to manipulate tuples by pushing/popping off their very first or very last member.

Is this something that needs to be proposed and added? What name could we even use without a potential conflict? Don't refer to it with "myTuple.last," but with a free function like "#tupleLast(myTuple)" instead? If that, how could we make that access mutable?

1 Like

I was testing out a function to do this, but during my testing I found that this code reliably causes the compiler to segfault:

func last<each T, U>(tuple: (repeat each T, u: U)) -> U {
  return tuple.u

print(last(tuple: (1, 2, u: 3)))

(I was hoping you could call this without the label, i.e. last(tuple: (1, 2, 3)), but evidently you can't call it at all.)

Edit: submitted Compiler segfault with variadic generics, grabbing last element of tuple · Issue #74218 · apple/swift · GitHub