在 Swift 中将列表从一个函数传递到另一个函数 [英] Passing lists from one function to another in Swift

查看:28
本文介绍了在 Swift 中将列表从一个函数传递到另一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不太明白为什么我不能将 Int[] 从一个函数传递到另一个函数:

I can't quite understand why I can't past an Int[] from one function to another:

func sumOf(numbers: Int...) -> Int {
    var sum = 0
    for number in numbers {
        sum += number
    }
    return sum
}

func average(numbers:Int...) -> Double {
    var sum = sumOf(numbers)

    return Double(sum) / Double(numbers.count)
}

这给了我以下错误:

Playground 执行失败:错误:<REPL>:138:19:错误:找不到接受所提供参数的__conversion"的重载

var sum = sumOf(numbers)
          ^~~~~~~~~~~~~~

感谢您的帮助!

推荐答案

sumOf 中的 numbers: Int... 参数称为可变参数.这意味着您可以传入该类型参数的可变数量,并且您传入的所有内容都将转换为该类型的数组供您在函数中使用.

The numbers: Int... parameter in sumOf is called a variadic parameter. That means you can pass in a variable number of that type of parameter, and everything you pass in is converted to an array of that type for you to use within the function.

因此,average 中的 numbers 参数是一个数组,而不是像 sumOf 这样的一组参数.

Because of that, the numbers parameter inside average is an array, not a group of parameters like sumOf is expecting.

您可能希望重载 sumOf 以接受其中之一,就像这样,这样您的平均函数就可以调用适当的版本:

You might want to overload sumOf to accept either one, like this, so your averaging function can call the appropriate version:

func sumOf(numbers: [Int]) -> Int {
    var sum = 0
    for number in numbers {
        sum += number
    }
    return sum
}
func sumOf(numbers: Int...) -> Int {
    return sumOf(numbers)
}

这篇关于在 Swift 中将列表从一个函数传递到另一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆