In this blog, we are going to learn about variadic parameters in swift. It is a parameter in which we can pass from zero to n numbers of variables and is used where the number of parameters is not defined. They are used in many functions in swift-like print which can take a variation of a number of arguments, it is defined as the value type by the three dots.
The syntax for the Variadic parameters in Swift.
1 2 3 |
func add(_ newContent: Int...) { } |
Now, please follow the below steps for the integration of the sample example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
struct Bucket { private(set) var container: [Milk] = [] mutating func add(_ newContent: Milk...) { container.append(contentsOf: newContent) } mutating func total() -> Int { var qty: Int = 0 for item in container { qty += item.qty } return qty } } |
Now add the milk to the bucket and call the total function to get the total amount of milk.
1 2 3 4 5 |
var bucket = Bucket() bucket.add(Milk(qty: 2, donorName: "Deepak Kumar")) bucket.add(Milk(qty: 3, donorName: "Rishab Sharma"), Milk(qty: 5, donorName: "Aman bhatt")) bucket.total() |
We can use the array or any other collection in place of the variadic parameters but in variadic we have to pass at least one parameter whereas in the array we can pass an empty array. However, for more details please check out the official Apple documentation from here.
Conclusion
I hope this blog will help you in understanding the functions with variable parameters. If you have queries, comments, and recommendations, feel free to post them in the comment section below. Please refer to my other blogs from here.