Reputation: 550
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
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