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

1

6

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 ?

Jonijonie answered 5/2, 2015 at 14:3 Comment(1)
Note that aToto.dynamicType.toto returns a curried function taking a class instance as its first parameter, because you are referencing it via its type (aToto.dynamicType). The equivalent for aToto.toto is Toto.toto(aToto) or aToto.dynamicType.toto(aToto)Waltman
O
12

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
Ottavia answered 5/2, 2015 at 14:13 Comment(6)
Which is equivalent to let f1: Void -> Void = aToto.toto and let f2: String -> Void = aToto.totoWaltman
@Antonio: You are right, thanks. (Actually I tried that first but must have make some error, because it did not compile initially.)Ottavia
Is there no difference between aToto.toto and aToto.dynamicType.toto ? The first returns a () -> Void while the second returns Toto -> () -> Void. I have a lib which take the second type as parameter so I thought I needed to get my func with dynamicType stuff. But aToto.dynamicType.toto as (String) -> Void returns the following error : String is not a subtype of TotoJonijonie
Right ! Thanks you both for these explanations ;)Jonijonie
@MartinR Do you know of a way to distinguish between methods with the same parameter types, but different external parameter names? This can be quite common in the case of delegate methods. Including the parameter name in the type declaration doesn't seem to help.Charcoal
@Stuart: It seems that this is not possible, compare #28285424.Ottavia

© 2022 - 2024 — McMap. All rights reserved.