Variadic Parameters in Swift

Variadic Parameters allows us to specific 'n' number for parameters to a function. This could be useful in scenarios where input count is unknown. ex: Addition of all numbers.


Below is a simple function implementation in Swift .



func addNumbers(addAllNumbers numberItems:Int...) -> Int{
    var total = 0
    for num in numberItems {
        total += num
    }
    
    return total
}





addNumbers(addAllNumbers: 1,2,3)


The answer this would be 6. Here we don't have to pass a array of Int, instead of that we pass input's as if there are multiple parameters (not inputs are ',' separated).

Now one important question arises here, Can a function have more than one variadic kind of parameter? 

Answer to this is NO.

There can be only one and only one variadic parameter.

Try to that and you will get the compile time error, as shown below.








Comments

Popular posts from this blog

hitTest on iOS to identify the view being hit

CMTimeMakeWithSeconds explained

How to set Custom Section Header in UITableView for ios sdk version greater than 6