You may see three dot ... operator in swift for two different cases:
1. ... as variadic parameter in function definition
A variadic parameter accepts zero or more values of a specified type. The parameters are separated with comma. The value of a variadic parameter in the function’s body is an array with the specified element type. A function can only have at most one variadic parameter.
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)
arithmeticMean()
2. ... as a closed range operator in statement
The closed range operator a...b creates a ClosedRange<T> object that contains elements from a to b inclusive. The value of a must not be greater than b. It is most used to enumerate all elements in a for loop
for index in 1...5 {
print("\(index) times 5 is \(index * 5)")
}
// 1 times 5 is 5
// 2 times 5 is 10
// 3 times 5 is 15
// 4 times 5 is 20
// 5 times 5 is 25
1. ... as variadic parameter in function definition
A variadic parameter accepts zero or more values of a specified type. The parameters are separated with comma. The value of a variadic parameter in the function’s body is an array with the specified element type. A function can only have at most one variadic parameter.
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)
arithmeticMean()
2. ... as a closed range operator in statement
The closed range operator a...b creates a ClosedRange<T> object that contains elements from a to b inclusive. The value of a must not be greater than b. It is most used to enumerate all elements in a for loop
for index in 1...5 {
print("\(index) times 5 is \(index * 5)")
}
// 1 times 5 is 5
// 2 times 5 is 10
// 3 times 5 is 15
// 4 times 5 is 20
// 5 times 5 is 25
No comments:
Post a Comment