arrays - 如何转发带有可变参数的函数?

标签 arrays swift variadic-functions

在 Swift 中,如何将数组转换为元组?

出现这个问题是因为我试图在一个接受可变数量参数的函数中调用一个接受可变数量参数的函数。

// 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
}

这个averageOf 实现对我来说似乎是合理的,但它不能编译。当您尝试调用 sumOf(numbers) 时出现以下错误:

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

averageOf 中,numbers 的类型为 Int[]。我相信 sumOf 需要一个元组而不是数组。

因此,在 Swift 中,如何将数组转换为元组?

最佳答案

这与元组无关。无论如何,在一般情况下不可能从数组转换为元组,因为数组可以有任意长度,并且必须在编译时知道元组的元数。

但是,您可以通过提供重载来解决您的问题:

// 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)

也许有更好的方法(例如,Scala 使用特殊的类型归属来避免需要重载;您可以在 averageOf< 中用 Scala sumOf(numbers: _*) 编写 没有定义两个函数),但我没有在文档中找到它。

关于arrays - 如何转发带有可变参数的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49380042/

相关文章:

arrays - 将数组名称作为 mongoose 中的参数传递

ios - 如何以编程方式设置字体大小以适应 swift 4 中的行数值

c++ - 专门化变量模板函数的问题

ios - 将 UIButton 放置在具有约束的 UIScrollView 底部

c# - 将数组解包到方法参数中

c - printf ("%x",1) 是否调用未定义的行为?

javascript - 我怎样才能访问用户在 VueJS 的这些 v-text-fields 中输入的数据?

c++ - 增量数字变化循环? (所有排列)

java - 当我的代码运行时,我似乎得到一个空值

swift - 条件协议(protocol)一致性?