如何消除重载函数的歧义

How to disambiguate overloaded functions

这是我在 Swift 中学习函数重载时编写的一个完全人为的示例。以下函数仅在 return 类型上有所不同(第一个函数隐式 returns Void / () 而其他 returns Int)。

func foo(x:Int, y:Int) {
}

func foo(x:Int, y:Int) -> Int {
  return 0
}

// Call the version which returns Int
let i: Int = foo(6, y: 7)

// Call the version which returns Void
let v: Void = foo(6, y: 7)

// Ambiguous
foo(6, y:7)  // How can I force a call to the Void version without using let/var?

// I thought this might work but doesn't
foo(6,y: 7) as (Int, Int) -> Void

有没有一种方法可以在不使用 let 的情况下调用 Void 版本,即某种类型的转换? 同样,我知道这是一个人为的例子,但我想了解这里的选项。

您可以通过转换结果来消除两个 foo 函数的歧义:

foo(6, y: 7) as Int

foo(6, y: 7) as Void

或者你可以施放 foo 本身:

(foo as (Int, y: Int) -> Int)(6, y: 7)

(foo as (Int, y: Int) -> Void)(6, y: 7)

注意:在这两种情况下都可以使用 () 代替 Void