可变参数Variadic Parameter
// 可变参数numbers相当于数组,使用的时候可以当做数组
func sum(_ numbers: Int...) -> Int {
var total = 0
for number in numbers {
total += number
}
return total
}
// 使用
sum(10, 20, 30, 40) // 100
注意:
- 1.一个函数最多只能有1个可变参数
- 2.紧跟在可变参数后面的参数不能省略参数标签
// 参数string不能省略标签
func test(_ numbers: Int..., string: String, _ other: String) { }
test(10, 20, 30, string: "Jack", "Rose")
应用示例-Swift自带的print函数
/// - Parameters:
/// - items: Zero or more items to print.
/// - separator: A string to print between each item. The default is a single space (`" "`).
/// - terminator: The string to print after all items have been printed. The
/// default is a newline (`"\n"`).
public func print(_ items: Any..., separator: String = " ", terminator: String = "\n")
print(1,2,3,4) // 1 2 3 4
// 可以自定义分隔符号
print(1,2,3,4, separator: "_") // 1_2_3_4