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

前端 未结 1 1474
青春惊慌失措
青春惊慌失措 2020-12-06 19:12

I\'m trying to get a reference to a function like so :

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


        
相关标签:
1条回答
  • 2020-12-06 20:04

    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
    
    0 讨论(0)
提交回复
热议问题