While I was learning about "Functions", I met an issue showing "Extraneous argument label 'number:' in call" error msg for my code. I wonder why I shouldn't place "number" in argument?
func makeIncrementer() -> ((Int) -> Int) {
func addOne(number: Int) -> Int {
return 1 number
}
return addOne
}
var increment = makeIncrementer()
increment(number: 7)
CodePudding user response:
The problem is that you're returning a (Int) -> Int
, which doesn't specify a name for its argument. Ideally, you'd want to write
func makeIncrementer() -> ((number: Int) -> Int)
but that isn't allowed in Swift:
function types cannot have argument labels; use '_' before 'number'
The best you can do is
func makeIncrementer() -> ((_ number: Int) -> Int)
This strategy might make your code a little clearer because giving the argument a name makes its purpose more obvious. Unfortunately, you still have to omit the number:
label when you call the returned function:
let increment = makeIncrementer()
increment(7) // <- no `number:` label
What's the rationale?
Specifying argument labels for function types was possible before Swift 3. The problem was that you could write
func add(numToAdd: Int) -> Int { ... }
func subtract(numToSubtract: Int) -> Int { ... }
let f: ((numToAdd: Int) -> Int) = subtract
and then calling f(numToAdd: 3)
would actually call subtract(numToSubtract: 3)
, which is quite surprising and can cause confusion.
Check out this proposal for the full rationale behind removing this feature.