Search code examples
objective-cfunctionswiftdynamictype

Swift - get reference to a function with same name but different parameters


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 ?


Solution

  • 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 as the first argument then you 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