sjwarner sjwarner - 2 months ago 42x
Swift Question

Is there an objective reason I can't have a single-element tuple with an element label?

In Swift up to and including Swift 3, I can't create a single-element tuple where the element is named. So

func foo() -> Bar
is fine whereas
func foo() -> (bar: Bar)
produces a compiler error.

I can, however, think of a few possible uses for this pattern, e.g.

func putTaskOnQueue() -> (receipt: CancellableTask)

func updateMyThing() -> (updatedSuccessfully: Bool)

...where the label is used to reduce ambiguity as to what the return value represents.

Obviously there are various ways I could re-design my apis to work around this limitation, but I'm curious as to why it exists.

Is this a compiler limitation? Would allowing element labels on 1-tuples break parsing of some other piece of grammar? Has this been discussed as part of the Swift Evolution system?

To be clear: I am not soliciting opinions as to the correctness of the examples above. I'm after explanations (if they exist) as to why this is not technically possible.


Yes, it's due to limitations in the compiler. There are no one-tuples in Swift at all. Every T is trivially convertible to and from (T). SE-110 and SE-111 should improve things, but I'm not sure it will be enough to make this possible and I don't believe any of the current proposals explicitly do make it possible.

It has been discussed on swift-evolution. It's not a desired feature of the language; it's a result of other choices.

The Swift Evolution process is very open. I highly recommend bringing questions like this to the list (after searching the archives; admittedly not as simple as you would like it to be). StackOverflow can only give hearsay; the list is much more definitive.