Swift 3闭包重载解析 [英] Swift 3 closure overload resolution
问题描述
我对函数重载解析和Swift 3中的闭包感到困惑。
I'm confused by function overload resolution with closures in Swift 3.
例如,在代码中:
func f<T>(_ a: T) {
print("Wide")
}
func f(_ a: (Int)->(Int)) {
print("Narrow")
}
f({(a: Int) -> Int in return a + 1})
我希望 Narrow
,而不是宽
打印到控制台。谁能解释为什么为非闭包参数选择了更具体的重载而不是闭包,或者这是编译器错误吗?
I expect Narrow
, not Wide
, to be printed to the console. Can anyone explain why the more specific overload gets chosen for non-closure arguments but not for closures or is this a compiler bug?
Swift 2表现出了预期的行为。
Swift 2 exhibited the expected behavior.
推荐答案
这可能是由于关闭参数的默认转义行为发生了变化。
This is probably due to the change in the default "escaping" behaviour for closure parameters.
如果将特定功能更改为:
If you change the specific function to :
func f(_ a:@escaping (Int)->Int)
{
print("Narrow")
}
它将按预期方式打印 Narrow(窄,这可能是您可能在其他几个更明显的地方所做的相同更改)
it will print "Narrow" as expected (this this the same change that you probably had to make in several other places that were more obvious)
这篇关于Swift 3闭包重载解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!