Swift should have a way to unpack an array into variadic parameters
| Originator: | brent | ||
| Number: | rdar://17284891 | Date Originated: | 12-Jun-2014 03:53 AM |
| Status: | Duplicate/12134482 | Resolved: | |
| Product: | Developer Tools | Product Version: | Xcode6-Beta (6A215l) |
| Classification: | Feature (New) | Reproducible: | Always |
Summary:
Suppose you have a variadic function:
func sum(x: Int…) …
And you have a matching array in your code:
let vars = [1, 2, 3]
Swift should have a mechanism to pass the array to the function by unpacking the array into the argument list.
Steps to Reproduce:
1. Write a variadic method, e.g.:
func sum(xs: Int…) -> Int { return reduce(xs, 0) { sum, num in sum + num } }
2. Declare a variable containing an Array with a matching type, e.g.:
let vars = [1, 2, 3]
3. Try to call the function with the array, using some appropriate syntax, e.g.:
sum(vars)
sum(*vars)
sum(vars…)
Expected Results:
There is some way to do this.
Actual Results:
There is no way to do this.
Notes:
The current best suggestion is to provide another version of the function that accepts an array:
func sum(vars: Int[]) -> Int { return reduce(xs, 0) { sum, num in sum + num } }
func sum(vars: Int…) { return sum(vars) }
This does work, but it’s kind of clunky.
The * syntax is based on Ruby and Perl 6. The … is my own suggestion, meant to match the … in a variadic signature. However, I actually think … might be better for indicating currying; I’ll file that bug eventually.
Comments
Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!
Another option is an "apply" function or method.
An "apply" function or method, would be similar to Clojure, or JavaScript respectively. Just adding another option here.
I saw a comment on stack overflow from someone who'd talked to an Apple employee about this at WWDC. This implication was that a splat operator is probably coming; just something they hadn't got around to yet.
I filed another radar for this.