geekhunger
geekhunger

Reputation: 550

Why Swift throws error when using optional param in closure func?

Can someone explain why the swift compiler complains about the "offset:" parameter which is optional anyway?

If I pass zero as param incrementByFive(0) then it works. But why would I bother doing so when I have a default value in closure definition...

code and its error image... Here's the code:

func makeIncrementer(amount: Int) -> (Int?) -> Int {
    var counter = 0

    func incrementer(_ offset: Int? = 0) -> Int {
        counter += amount + offset!
        return counter
    }

    return incrementer
}


let incrementByFive = makeIncrementer(amount: 5)
incrementByFive()

Upvotes: 0

Views: 77

Answers (1)

Martin R
Martin R

Reputation: 540105

Only functions can have default parameters in Swift, but not closures.

The closure returned from makeIncrementer() has the type (Int?) -> Int, i.e. it takes one argument of type Int?, and that must be provided when calling the closure.

Compare also SR-531 Allow default parameters in closure parameters, in particular the comment

Doesn't really make sense, if you need this behavior you should be using a function. Closures are usually called anonymously with their arguments all provided, so there is no need for default parameter values.

Upvotes: 1

Related Questions