Swift - 将重载函数分配给变量

Mat*_*t H 7 swift

我得到一个编译时错误,myFunc引用是不明确的.

func f (s: String) -> String { return "version 1: " + s }
func f(sourceString s: String) -> String { return "version 2: " + s }
var myFunc: (String)-> String = f as (sourceString : String)->String
Run Code Online (Sandbox Code Playgroud)

在上面的示例中,如何显式引用重载函数f的每个版本?如果我注释掉它的任何声明func f将编译和工作.但我想知道如果声明这两个函数,如何引用每个函数.谢谢.

Mar*_*ino 5

我不知道怎么做你想要的,但也许这会有所帮助:

var myFunc1: (String)-> String = { s in f(sourceString: s) }
var myFunc2: (String)-> String = { s in f(s) }
Run Code Online (Sandbox Code Playgroud)

你现在可以打电话:

let s1 = myFunc1("one")  // returns "version 2: one"
let s2 = myFunc2("two")  // returns "version 1: two"
Run Code Online (Sandbox Code Playgroud)


Air*_*ity 4

有趣的是这个。我不认为\xe2\x80\x99t 认为\xe2\x80\x99s 可能不按照@marcos\xe2\x80\x99s 建议做一些事情。您的问题是您可以 \xe2\x80\x9ccast 掉 \xe2\x80\x9d 元组中的名称:

\n\n
let named_pair = (s: "hello", i: 1)\nnamed_pair.s  // hello\n\nlet anon_pair = named_pair as (String,Int)\n// or anon_pair: (String,Int) = named_pair, if you prefer\nanon_pair.s  // no such member \'s\'\n
Run Code Online (Sandbox Code Playgroud)\n\n

现在假设您定义了两个函数,除了其中一个具有命名参数之外,它们完全相同:

\n\n
func f(s: String, i: Int) { println("_: \\(s)") }\nfunc f(#s: String, #i: Int) { println("s: \\(s)") }\n
Run Code Online (Sandbox Code Playgroud)\n\n

然后,您可以通过带有命名和未命名参数的元组来调用它:

\n\n
f(named_pair)  // prints s: hello\nf(anon_pair)   // prints _: hello\n\n// but if you try to call a named argument function with unnamed tuples:\nfunc g(# s: String, # i: Int) { println("s: \\(s)") }\ng(anon_pair)  // compiler error\n\nlet h = g\nh(anon_pair)   // compiler error\nh(named_pair)  // works\n
Run Code Online (Sandbox Code Playgroud)\n\n

但是因为你可以丢弃这些名称,所以你可以这样做:

\n\n
// compiles and runs just fine...\n(g as (String,Int)->())(anon_pair)\nlet k: (String,Int)->() = g\n// as does this\nk(anon_pair)\n
Run Code Online (Sandbox Code Playgroud)\n\n

据我所知,这种能力意味着\xe2\x80\x99不可能使用类型来消除仅通过参数名称重载的函数的歧义。

\n