[swift-evolution] array splatting for variadic parameters
Cao, Jiannan
frogcjn at 163.com
Thu Nov 30 15:12:47 CST 2017
What happened with this proposal? This looks easy to implement.
func sumOf(numbers: Int...) -> Int {
...
}
typealias Function = [Int] -> Int
let sumOfArray = unsafeBitCast(sumOf, Function.self)
sumOfArray([1, 2, 3])
> Hello everyone.
>
> I understand that topic has already been discussed in the past, but I failed to get any information on its current state of affairs.
>
> I guess the subject of this mail is explicit, but to make sure I’m clear, here's a small snippet that illustrates the problem:
>
> func f(args: Int…) {
> // Some implementation ...
> }
> // Now it's impossible to call f without explicitly naming its parameters.
>
> For many use-cases, this problem can be solved by overloading f so that it explicitly accepts an array.
>
> func f(_ args: [Int]) {
> // Some implementation ...
> }
>
> func f(_ args: Int…) {
> f(args)
> }
>
> Some people also advocate (myself generally included) that one should prefer the signature explicitly marking args as an array, as the syntactic overhead of wrapping the arguments with “[]” when calling f is arguably bearable. However, in some other situations, this approach might not be applicable. For instance, one may simply not be able to modify the original function. Another use-case may be a function that should forward its own variadic parameters.
>
> In a variety of other languages, there exists a way to do this. For instance, Python can “unpack” (or splat) a list into function arguments by prefixing it with *:
>
> def f(*args):
> # Some implementation …
>
> f(*[1, 2, 3]) # == f(1, 2, 3)
>
> I was wondering if such feature could be supported by Swift, and if not, why.
>
> Syntactically, I like the use of “…”, which would mirror function signatures:
>
> f(…[1, 2, 3]) // == f(1, 2, 3)
>
> Thanks.
>
> --
> Dimitri Racordon
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20171201/930a1f8b/attachment.html>
More information about the swift-evolution
mailing list