0

My Question is the below example in function and closure why we need to use this line

func sumOf(numbers: Int...) with three dots (...) ?

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

what is meaning for these dots ??

1

6 Answers 6

1

Those ... mean that the function can take a variable number of arguments

From the The Swift Programming Language book:

Variadic Parameters

A variadic parameter accepts zero or more values of a specified type. You use a variadic parameter to specify that the parameter can be passed a varying number of input values when the function is called. Write variadic parameters by inserting three period characters (...) after the parameter’s type name.

The values passed to a variadic parameter are made available within the function’s body as an array of the appropriate type. For example, a variadic parameter with a name of numbers and a type of Double... is made available within the function’s body as a constant array called numbers of type [Double].

Sign up to request clarification or add additional context in comments.

Comments

1

I do not know about Swift, but in other languages such as ActionScript, the dots means you can pass more than one argument to the method and they will be interpreted as an array.

For example:

    sumOf(1, 3, 6);

Comments

1

This is known as a variadic parameter and accepts zero or more Int values. For more information see https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Functions.html

Comments

1

It means you can pass in any number of ints rather than an explicitly specified number

if you said

func sumOf(num1: Int, num2: Int) -> Int

you could only sum 2 Ints and you would need to write a new function for 3 and 4 etc.

In essence it is a shorthand for writing

func sumOf(numbers :[Int]) -> Int

which does not require the caller to wrap the numbers in an array.

see https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Functions.html#//apple_ref/doc/uid/TP40014097-CH10-ID171

Comments

1

The ... here represent that the function can take as many number of arguments of type Int.

You can consider this as you're passing an array as a parameter except that you are not gonna use the Square Notation([]).

Comments

1

This means that the function can take variable number of arguments, collecting them into an array.

and that parameter, in your case numbers is called variadic parameter.

Note, in swift 2, a function can have maximum one variadic parameter

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.