Single-element tuples; do it like Rust?

Did we all miss an easy solution?

I was refreshing myself on Rust's array syntax, and I noticed this in another section of its punctuator list:

  • "( expression )" is an expression surrounded by parentheses
  • "( expression , )" is a single-element tuple expression
  • "( type , )" is a single-element tuple type

When having a single item surrounded by parentheses, just adding a trailing comma before the closing parenthesis differentiates singular expressions from tuple ones. I know some list expressions during Swift parsing allow trailing commas; would those interfere from us ripping off Rust to allow this way to indicate single-item tuples?

4 Likes

Python uses the same syntax, and it would probably be a good candidate, but I don't think the real question for Swift is how to spell the single-element tuple. The discussions that I have read have been around why to have single-element tuples, what are the implications for a hypothetical variadic generics system, should you be allowed to have labelled single-element tuples even if unlabelled ones are disallowed, etc.

2 Likes

My 2 cents are:

Personally I think tuples should become auto generated structs of generic Tuple type which has the ability to assign type parameter labels to it's properties, or something along the lines. That Tuple type should also conform to a new ExpressibleByTupleLiteral protocol. That protocol will only allow tuples of at least one element. The empty tuple () should fall back to struct Void { init() {} } or an in-extensible enum with one case. Tuples would be easy extensible, no more need for special syntaxes. We could conform our types to support tuple literals but by default a tuple literal would infer to Tuple<...> just like the array literal falls back to [Type].

I can't tell if this is a reasonable way for Swift to evolve, but that's just my opinion how I'd prefer it. Furthermore I definitely wouldn't want to see a (type,) syntax, because it feels not right, since it only aims for disambiguation.


If you would like to push this topic further, I encourage you to look up the previous threads and provide a summary of what already has been said and considered. That way we don't need to re-hash everything over again.

5 Likes