本文介绍了Swift - 获取具有相同名称但参数不同的函数的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
class Toto {
func toto (){println(f1)}
func toto(aString:String){println(f2)}
}
var aToto:Toto =
var f1 = aToto.dynamicType.toto
我有以下错误: toto的含糊使用
如何获得指定参数的函数?
有两个名称相同但签名不同的方法,所以您必须指定哪一个想要:
let f1 = aToto.toto as() - > void
let f2 = aToto.toto as(String) - >无效
f1()//输出:f1
f2(foo)//输出:f2
或者(正如@Antonio正确指出的那样):
let f1:() - > Void = aToto.toto
let f2:String - > Void = aToto.toto
如果您需要将类的实例作为$ b $的curried函数b第一个参数,然后
,您可以用相同的方式继续,只有签名是不同的
(比较@Antonios对您的问题的评论):
let cf1:Toto - > () - > Void = aToto.dynamicType.toto
让cf2:Toto - > (字符串) - > Void = aToto.dynamicType.toto
cf1(aToto)()//输出:f1
cf2(aToto)(bar)//输出:f2
I'm trying to get a reference to a function like so :
class Toto { func toto() { println("f1") } func toto(aString: String) { println("f2") } } var aToto: Toto = Toto() var f1 = aToto.dynamicType.toto
I have the following error : Ambiguous use of toto
How do I get function with specified parameters ?
解决方案
Since Toto has two methods with the same name but different signatures,you have to specify which one you want:
let f1 = aToto.toto as () -> Void let f2 = aToto.toto as (String) -> Void f1() // Output: f1 f2("foo") // Output: f2
Alternatively (as @Antonio correctly noted):
let f1: () -> Void = aToto.toto let f2: String -> Void = aToto.toto
If you need the curried functions taking an instance of the class asthe first argument thenyou can proceed in the same way, only the signature is different(compare @Antonios comment to your question):
let cf1: Toto -> () -> Void = aToto.dynamicType.toto let cf2: Toto -> (String) -> Void = aToto.dynamicType.toto cf1(aToto)() // Output: f1 cf2(aToto)("bar") // Output: f2
这篇关于Swift - 获取具有相同名称但参数不同的函数的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
07-30 02:14