Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
956 views
in Technique[技术] by (71.8m points)

arrays - How to forward functions with variadic parameters?

In Swift, how do you convert an Array to a Tuple?

The issue came up because I am trying to call a function that takes a variable number of arguments inside a function that takes a variable number of arguments.

// Function 1
func sumOf(numbers: Int...) -> Int {
    var sum = 0
    for number in numbers {
        sum += number
    }
    return sum
}
// Example Usage
sumOf(2, 5, 1)

// Function 2
func averageOf(numbers: Int...) -> Int {
    return sumOf(numbers) / numbers.count
}

This averageOf implementation seemed reasonable to me, but it does not compile. It gives the following error when you try to call sumOf(numbers):

Could not find an overload for '__converstion' that accepts the supplied arguments

Inside averageOf, numbers has the type Int[]. I believe sumOf is expecting a Tuple rather than an Array.

Thus, in Swift, how do you convert an Array to a Tuple?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This has nothing to do with tuples. Anyway, it isn't possible to convert from an array to a tuple in the general case, as the arrays can have any length, and the arity of a tuple must be known at compile time.

However, you can solve your problem by providing overloads:

// This function does the actual work
func sumOf(_ numbers: [Int]) -> Int {
    return numbers.reduce(0, +) // functional style with reduce
}

// This overload allows the variadic notation and
// forwards its args to the function above
func sumOf(_ numbers: Int...) -> Int {
    return sumOf(numbers)
}

sumOf(2, 5, 1)

func averageOf(_ numbers: Int...) -> Int {
    // This calls the first function directly
    return sumOf(numbers) / numbers.count
}

averageOf(2, 5, 1)

Maybe there is a better way (e.g., Scala uses a special type ascription to avoid needing the overload; you could write in Scala sumOf(numbers: _*) from within averageOf without defining two functions), but I haven't found it in the docs.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...