可变形参
一个可变形参可接受零个或多个指定类型的值。当函数被调用时,你可以使用可变形参来 指定--形参可以用来传递任意数量的输入值。可通过在形参的类型名后边插入三个点符号(...)来编写可变形参。
传递至可变形参的值在函数主体内是以适当类型的数组存在的。例如,一个可变参数的名称为 numbers 和类型为 Double...在函数体内就作为名为 numbers 类型为 Double[]的常量数 组。
下边示例为任何长度的数字列表计算算术平均值:
func arithmeticMean(numbers: Double...) -> Double {
var total: Double = 0
for number in numbers {
}
return total / Double(numbers.count)
total += number
}
arithmeticMean(1, 2, 3, 4, 5)
// returns 3.0, which is the arithmetic mean of these five numbers
arithmeticMean(3, 8, 19)
// returns 10.0, which is the arithmetic mean of these three numbers
注意:函数最多可以有一个可变形参,而且它必须出现在参数列表的最后,以避免使
用多个形参调用函数引发歧义。如果你的函数有一个或多个带有默认值的形参,并且
还有可变形参,请将可变形参放在所有默认形参之后,也就是的列表的最末尾。