Swift 3 closure overload resolution

流过昼夜 提交于 2019-12-07 15:55:44

问题


I'm confused by function overload resolution with closures in Swift 3.

For example, in the code:

func f<T>(_ a: T) {
    print("Wide")
}

func f(_ a: (Int)->(Int)) {
    print("Narrow")
}

f({(a: Int) -> Int in return a + 1})

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 exhibited the expected behavior.


回答1:


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")
}

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)



来源:https://stackoverflow.com/questions/39802434/swift-3-closure-overload-resolution

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!