2016-12-24 63 views
1

我是新来的swift 3.我有现有的代码,并希望将其转换为swift 3.我只是好奇为什么xcode要求我在参数名称前插入_为什么swift 3在闭包参数中需要`_`?

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

我在网上搜索它,但我找不到答案。如果你有一个更好的方法来创建具有多个值的闭包,以便传递给处理程序,请在下面评论。

感谢

+0

https://github.com/apple/swift-evolution/blob/master/proposals/0111-remove-arg-label-type-significance.md – Alexander

回答

0

斯威夫特3之前,参数名称是类型的一部分,只要该类型的系统而言。但是,强制使用关键字名称进行适当匹配会导致使用关闭的噩梦。因此,类型系统忽略了它们,这引出了为什么它们是名字中类型的一部分的问题。

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) 
相关问题