2016-12-24 61 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) 
相關問題