How to use variadic function that accept any number of parameters in Swift

2 Answers

0 votes
func sum(_ numbers: Int...) -> Int {
    var total = 0

    for number in numbers {
        total += number
    }

    return total
}


var total = sum(1, 2, 3, 4, 5, 6)
print("total = \(total)")

total = sum(5, 9, 1)
print("total = \(total)")




/*
run:

total = 21
total = 15

*/

 



answered Feb 12, 2021 by avibootz
0 votes
public func function(_ year:Int, _ names:String...) -> () {
    
    print("\(year)")
    
    for s in names { 
        print("\(s)")
    }
}

function(1810, "Hump", "Cornholder", "Dump", "Head")
print("")
function(1920, "Phuckzer", "R2D2", "Torres")




/*
run:

1810
Hump
Cornholder
Dump
Head

1920
Phuckzer
R2D2
Torres

*/

 



answered Jun 13, 2023 by avibootz
...