2015-02-05 53 views
5
功能

我试图让像这样的函数的引用:斯威夫特 - 获得参考与同名但不同参数

class Toto { 
    func toto() { println("f1") } 
    func toto(aString: String) { println("f2") } 
} 

var aToto: Toto = Toto() 
var f1 = aToto.dynamicType.toto 

我有以下错误:Ambiguous use of toto

怎么办我得到具有指定参数的函数?

+0

注意'aToto.dynamicType.toto'返回咖喱函数采取一个类的实例作为其第一个参数,因为您是通过其类型引用它('aToto .dynamicType')。 'aToto.toto'的等价物是'Toto.toto(aToto)'或'aToto.dynamicType.toto(aToto)' – Antonio 2015-02-05 14:18:30

回答

9

由于Toto有两种方法具有相同的名称但不同的签名, 你必须指定你想要哪一个:

let f1 = aToto.toto as() -> Void 
let f2 = aToto.toto as (String) -> Void 

f1()   // Output: f1 
f2("foo") // Output: f2 

或者(如@Antonio正确地指出):

let f1:() -> Void  = aToto.toto 
let f2: String -> Void = aToto.toto 

如果您需要使用该类的实例作为 第一个参数然后 您可以以相同的方式继续,只有签名是不同的 (与你的问题@Antonios评论):

let cf1: Toto ->() -> Void  = aToto.dynamicType.toto 
let cf2: Toto -> (String) -> Void = aToto.dynamicType.toto 

cf1(aToto)()   // Output: f1 
cf2(aToto)("bar") // Output: f2 
+0

这相当于'let f1:Void - > Void = aToto.toto'和'let f2 :String - > Void = aToto.toto' – Antonio 2015-02-05 14:16:29

+0

@Antonio:你说得对,谢谢。 (其实我是先试过,但一定有错误,因为它最初并没有编译。) – 2015-02-05 14:20:14

+0

'aToto.toto'和'aToto.dynamicType.toto'没有区别吗?第一个返回'() - > Void',而第二个返回'Toto - >() - > Void'。我有一个采用第二种类型作为参数的lib,所以我认为我需要用'dynamicType'的东西来获得我的func。但'aToto.dynamicType.toto as(String) - > Void'返回以下错误:'字符串不是Toto的子类型@ – Yaman 2015-02-05 14:27:14