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.
To generate a tuple with one element, a comma , is required at the end. For example, when connecting multiple tuples with the + operator, note that an error is raised if you try to add one element and forget a comma , .
To create a tuple with only one item, you have add a comma after the item, unless Python will not recognize the variable as a tuple.
1 Answer. While creating a tuple with a single element, add a comma at the end of the element. In the absence of a comma, Python will consider the element as an ordinary data type; not a tuple. Creating a Tuple with one element is called “Singleton” tuple.
How to assign a tuple of length 1 to a? A parenthesized expression list yields whatever that expression list yields: if the list contains at least one comma, it yields a tuple; otherwise, it yields the single expression that makes up the expression list.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With