Monday, November 29, 2021

Swift: Three dot operator

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 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
And from the Swift documentation:
A variadic parameter accepts zero or more values of a specified type. You use a variadic parameter to specify that the parameter can be passed a varying number of input values when the function is called. Write variadic parameters by inserting three period characters (...) after the parameter’s type name. The values passed to a variadic parameter are made available within the function’s body as an array of the appropriate type. For example, a variadic parameter with a name of numbers and a type of Double... is made available within the function’s body as a constant array called numbers of type [Double].

No comments:

Post a Comment