【发布时间】:2020-08-09 21:38:28
【问题描述】:
我是 Swift 新手,在理解可变参数究竟是什么以及为什么它有用时遇到了一些麻烦。我目前正在关注在线 Swift 5.3 指南,这是为此类参数提供的示例。
func arithmeticMean(_ numbers: Double...) -> Double {
var total: Double = 0
for number in numbers {
total += number
}
return total / Double(numbers.count)
}
arithmeticMean(1, 2, 3, 4, 5)
// returns 3.0, which is the arithmetic mean of these five numbers
arithmeticMean(3, 8.25, 18.75)
// returns 10.0, which is the arithmetic mean of these three numbers
显然,名为numbers 的可变参数具有Double... 的类型,这允许它在函数体中作为常量数组使用。为什么函数返回Double(numbers.count) 而不仅仅是numbers.count?而不是创建一个可变参数,为什么不直接创建一个参数来接收一个像这样的函数之外的数组呢?
func addition(numbers : [Int]) -> Int
{
var total : Int = 0
for number in numbers
{
total += number
}
return total
}
let totalBruhs : [Int] = [4, 5, 6, 7, 8, 69]
addition(numbers: totalBruhs)
另外,为什么每个函数只能有一个可变参数?
【问题讨论】:
-
“为什么函数返回
Double(numbers.count)而不仅仅是numbers.count?” ... 它不是。它返回值的总和(这是一个双精度数)除以有多少数字。但是number.count是一个整数,你不能将Double除以一个整数。因此,在除法运算中使用它之前,您必须将整数计数转换为双精度数。这就是return表达式中Double(numbers.count)的意义所在。 -
FWIW,我不会使用可变参数来计算数字序列的平均值。再说一次,我也不会在
Double的数组上这样做。我可能会在Sequence上执行此操作并使用FloatingPoint协议。例如,gist.github.com/robertmryan/92edae4b0ca41455ad26253770a7fc5c