30000ft
30000ft

Reputation: 28

What's the difference between `Int...` and `[Int]` in Swift?

// first segment
func hasAnyMatches(list: [Int], condition: Int -> Bool) -> Bool {
    for item in list {
        if condition(item) {
            return true
        }
    }
    return false
}
func lessThanTen(number: Int) -> Bool {
    return number < 10
}
var numbers = [20, 19, 7, 12]
hasAnyMatches(numbers, condition: lessThanTen)

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

What's the difference between list in segment 1 and numbers in segment 2? Why one is [Int] another is Int...?

I try to exchange them in playground, error was shown.

Upvotes: 0

Views: 757

Answers (2)

attolee
attolee

Reputation: 622

[Int]

This indicates the parameter is a array type.

Int...

This indicates the parameter is a variadic parameter. A variadic parameter accepts zero or more values of a specified type.

Difference

A variadic parameter is used as a constant array within function body, the difference happens in calling function, we can call function with variadic parameter in none parameter style, like function_variadic_type(), and function with array type can't do this, there must be a array passed into function, like function_array_type([1, 2]).

Upvotes: 1

LIH
LIH

Reputation: 933

It has no difference. Your code is fine. You just have to delete 'condition' in line 17. The code should be like this

func hasAnyMatches(list: [Int], condition: Int -> Bool) -> Bool {
    for item in list {
        if condition(item) {
            return true
        }
    }
    return false
}
func lessThanTen(number: Int) -> Bool {
    return number < 10
}
var numbers = [20, 19, 7, 12]
hasAnyMatches(numbers, lessThanTen)

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

Upvotes: 0

Related Questions