我想说你的问题是你不明确地告诉编译器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") }
你会得到相同的结果。