Swift: generic overloads, definition of “more specialized”

只谈情不闲聊 提交于 2020-06-26 14:16:32

问题


In the below example, why is the foo(f) call ambiguous? I understand that the second overload could also apply with P == (), but why isn't the first one considered more specialized, and therefore a better match?

func foo<R>(_ f: () -> R) { print("r") }
func foo<P, R>(_ f: (P) -> R) { print("pr") }

let f: () -> Int = { 42 }
foo(f)   //  "Ambiguous use of 'foo'"

回答1:


I'd say your problem is that you don't explicitely tell the compiler that P == ()

try the following code in a playground :

Void.self == (Void).self // true
Void() == () // true
(Void)() == () // true
(Void) == () // Cannot convert value of type '(Void).Type' to expected argument type '()'

Foo<Int>.self == (() -> Int).self // false
(() -> Int).self == ((Void) -> Int).self // false
Foo<Int>.self == ((Void) -> Int).self // true

Since (Void) cannot be converted to (), I guess the compiler can't understand that foo<R>(_ f: () -> R) is actually a specialization of foo<P, R>(_ f: (P) -> R).

I suggest you create generic type aliases for your function types to help the compiler understand what you're doing eg. :

typealias Bar<P, R> = (P) -> R
typealias Foo<R> = Bar<Void, R>

Now you can can define your function like that :

func foo<R>(_ f: Foo<R>) { print("r") } // Note that this does not trigger a warning.
func foo<P, R>(_ f: Bar<P, R>) { print("pr") }

and then use them with any closure you want :

let f: () -> Int = { 42 }
foo(f)   // prints "r"
let b: (Int) -> Int = { $0 }
foo(b) // prints "pr"
let s: (String) -> Double = { _ in 0.0 }
foo(s) // prints "pr"

But you can actually just write :

func foo<R>(_ f: (()) -> R) { print("r") }
func foo<P, R>(_ f: (P) -> R) { print("pr") }

or even :

func foo<R>(_ f: (Void) -> R) { print("r") } // triggers warning :
// When calling this function in Swift 4 or later, you must pass a '()' tuple; did you mean for the input type to be '()'?
func foo<P, R>(_ f: (P) -> R) { print("pr") }

and you get the same results.



来源:https://stackoverflow.com/questions/62383640/swift-generic-overloads-definition-of-more-specialized

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