Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift:通用重载,定义;“更专业化”;_Swift_Generics_Overload Resolution - Fatal编程技术网

Swift:通用重载,定义;“更专业化”;

Swift:通用重载,定义;“更专业化”;,swift,generics,overload-resolution,Swift,Generics,Overload Resolution,在下面的示例中,为什么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'" func-

在下面的示例中,为什么
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'"
func-foo(f:()->R){print(“R”)}
func-foo(f:(P)->R){print(“pr”)}
设f:()->Int={42}
foo(f)/“foo”的模糊用法”

我想说你的问题是你没有告诉编译器
p==()

在操场上尝试以下代码:

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

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

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") }
但实际上你可以写:

func foo<R>(_ f: (()) -> R) { print("r") }
func foo<P, R>(_ f: (P) -> R) { print("pr") }
func-foo(f:(())->R){print(“R”)}
func-foo(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") }
func-foo(f:(Void)->R){print(“R”)}//触发警告:
//在Swift 4或更高版本中调用此函数时,必须传递一个“()”元组;您的意思是输入类型为“()”?
func-foo(f:(P)->R){print(“pr”)}

你也会得到同样的结果。

哦,很好。我缺少的关键洞见是
(P0..Pn)->R
vs
((P0..Pn))->R
。非常感谢。(有趣的是,相同的元组解构技巧在泛型类'init()中似乎不起作用。)
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") }