10

I want to make a method that can take variable number of parameters. Kind of like in javascript where I can get all the parameters using arguments keyword inside the function. How can I do this in Swift?

My main purpose is to allow all overloaded constructors to go to one method even if it has no parameters passed in it at all.

class Counter {
    var count: Int = 0
    func incrementBy(amount: Int, numberOfTimes: Int) {
        count += amount * numberOfTimes
    }
}

4 Answers 4

21

There is an example of that in the Swift iBook, page 17:

func sumOf(numbers: Int...) -> Int {
    var sum = 0
    for number in numbers {
        sum += number
    }
    return sum
}

sumOf()             // returns 0
sumOf(1,2)          // returns 3
sumOf(42, 597, 12)  // returns 651
Sign up to request clarification or add additional context in comments.

Comments

14

Varargs are great, but they aren't really for optional parameters that mean different things, as seen in the Counter example in the question. Function overloading can be kind of excessive, though: it breaks the coupling between a function definition and its true implementation.

What you might want here is default values for parameters:

func incrementBy(amount: Int, numberOfTimes num: Int = 1) {
    count += amount * num
}

Now you'll get the same behavior calling either incrementBy(2, numberOfTimes:1) or incrementBy(2) (incrementing by two, once).

Parameters with default values must come last in in the func/method signature, and must be labeled. This is discussed a few subsections down under Function Parameter Names in the book.

Comments

3

They call them Variadic Parameters in Swift, and the notation is as follows:

func aFunction(args: String...) {
    println(args[0])
    // do other stuff
}

aFunction("something", "something else")

I've given the parameters the name "args" here, but that isn't part of the syntax, it can be called what ever you want. The important part is the trailing periods (...). You can access the individual arguments via their subscript.

More info can be found in The Swift Programming Language on page 227.

Comments

2

You can overload functions in Swift.

func test(amount: Int) {
    test(amount, nil)
}

func test(amount: Int, name: String?) {
    println("Amount: \(amount)")
    if let name = name {
        println("Name: \(name)")
    }
}

test(1, "Leandros")
test(1)

This example would print:

Amount: 1
Name: Leandros
Amount: 1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.