Swift:泛型重载,“更专业”的定义

2023-11-30

在下面的例子中,为什么foo(f)叫暧昧? 我知道第二个重载也可以适用P == (), 但为什么第一个不被认为更专业, 因此是更好的匹配?

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'"

我想说你的问题是你不明确地告诉编译器P == ()

在 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)不能转换为(),我猜编​​译器无法理解这一点foo<R>(_ f: () -> R)实际上是一个专业化foo<P, R>(_ f: (P) -> R).

我建议你创建泛型类型别名对于您的函数类型,以帮助编译器理解您在做什么,例如。 :

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

现在你可以这样定义你的函数:

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

然后将它们与您想要的任何闭包一起使用:

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"

但实际上你可以这样写:

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

甚至 :

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

你会得到相同的结果。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Swift:泛型重载,“更专业”的定义 的相关文章

随机推荐