Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 728
Yaman Avatar asked Feb 05 '15 14:02

Yaman


People also ask

Can you define multiple functions with the same identifier?

Yes, it's called function overloading. Multiple functions are able to have the same name if you like, however MUST have different parameters.

Which of following techniques can be used to define 2 functions that have same name and are in same class?

Function overriding in C++ is a concept by which you can define a function of the same name and the same function signature (parameters and their data types) in both the base class and derived class with a different function definition.

What is Variadic parameters in Swift?

In Swift, variadic parameters are the special type of parameters available in the function. It is used to accept zero or more values of the same type in the function. It is also used when the input value of the parameter is varied at the time when the function is called.

When a programmer defines multiple function with the same name it is called?

Overloaded functions in swift error.


1 Answers

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
like image 168
Martin R Avatar answered Sep 19 '22 12:09

Martin R