Swift should have a way to unpack an array into variadic parameters

Originator:benchatelain
Number:rdar://24578381 Date Originated:09-Feb-2016 04:56 PM
Status:Open Resolved:
Product:Developer Tools Product Version:Xcode6-Beta (6A215l)
Classification:Feature (New) Reproducible:Always
 
This is a duplicate of rdar://17284891

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!