加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 05:25:58 所属栏目:百科 来源:网络整理
导读:我得到一个编译时错误,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 如何
我得到一个编译时错误,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

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

有趣的是这个.如果不按照@ marcos的建议行事,我认为这是不可能的.您遇到的问题是“丢弃”元组中的名称:
let named_pair = (s: "hello",i: 1)
named_pair.s  // hello

let anon_pair = named_pair as (String,Int)
// or anon_pair: (String,Int) = named_pair,if you prefer
anon_pair.s  // no such member 's'

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

func f(s: String,i: Int) { println("_: (s)") }
func f(#s: String,#i: Int) { println("s: (s)") }

然后,您可以通过名为vs unnamed arguments的元组调用它:

f(named_pair)  // prints s: hello
f(anon_pair)   // prints _: hello

// but if you try to call a named argument function with unnamed tuples:
func g(# s: String,# i: Int) { println("s: (s)") }
g(anon_pair)  // compiler error

let h = g
h(anon_pair)   // compiler error
h(named_pair)  // works

但是因为你可以抛弃这些名字,你可以这样做:

// compiles and runs just fine...
(g as (String,Int)->())(anon_pair)
let k: (String,Int)->() = g
// as does this
k(anon_pair)

而这种做到这一点的能力意味着,就我所知,不可能使用类型来消除仅由参数名称重载的函数的歧义.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读