1

I'm new to swift 3. I have existing code and want to convert it to swift 3. I'm just curious why xcode is requiring me to insert _ before the parameter name.

func anotherClosure(age: Int, name: String, handler: (_ name: String, _ age: Int) -> ()) {
        handler(name, age)
    }

I'm searching it on the net but I couldn't find the answer. and if you have a better way of creating closures with multiple values to be pass on the handler please comment below.

Thanks

Alvin John
  • 403
  • 4
  • 14
  • https://github.com/apple/swift-evolution/blob/master/proposals/0111-remove-arg-label-type-significance.md – Alexander Dec 24 '16 at 06:41

1 Answers1

0

Prior to Swift 3, parameter names were part of the type, so far as the type system was concerned. However, enforcing that the keyword names be properly matched up would've made using closures a nightmare. Thus, the type system ignored them, which begs the question why they're part of the type in the first name.

import CoreFoundation

func applyAndPrint(closure: (a: Double, b: Double) -> Double, _ a: Double, _ b: Double) {
    print(a, b, closure(a: a, b: b))
}

//All these have different types, because of their different keyword parameter names.
let adder: (augend: Double, addend: Double) -> Double = { $0 + $1 }
let subtractor: (minuend: Double, subtrahend: Double) -> Double = { $0 - $1 }
let multiplier: (multiplicand: Double, multiplier: Double) -> Double = { $0 * $1 }
let divider: (dividend: Double, divisor: Double) -> Double = { $0 / $1 }
let exponentiator: (base: Double, exponent: Double) -> Double = { pow($0, $1) }
let rooter: (degree: Double, Radicand: Double) -> Double = { pow($1, 1/$0) }

// Yet the type system ignores that, and all these are valid:
applyAndPrint(adder, 2, 3)
applyAndPrint(subtractor, 2, 3)
applyAndPrint(multiplier, 2, 3)
applyAndPrint(divider, 2, 3)
applyAndPrint(exponentiator, 2, 3)
applyAndPrint(rooter, 2, 3)
Alexander
  • 59,041
  • 12
  • 98
  • 151