func sumOf(numbers: Int...) -> Int {
var sum: Int = 0
for number in numbers {
sum += number
}
return sum
}
sumOf(1, 2, 3) //6
This is sample code taken from the Swift
iBook. It finds the sum of any number of arguments.
A python equivalent of this code would be:
def sumOf(*args):
sum = 0
for number in args:
sum += number
return sum
sumOf(1, 2, 3) #6
In python, *args accepts all variable types, so if I want to do this for whatever reason, I can:
def sumOf(*args):
sum = ""
for number in args:
sum += str(number)
return sum
sumOf(1, "test", 3) #"1test3"
How do I do this in Swift
? How do I create a function that has a variable number of parameters of ANY TYPE? I don't need to do this, but I'd like to know how.
Thanks.
Something like this?
func concatOf(args: Any...) -> String {
var concat = ""
for arg in args {
concat = "\(concat)\(arg)"
}
return concat
}