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 ?
Yes, it's called function overloading. Multiple functions are able to have the same name if you like, however MUST have different parameters.
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.
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.
Overloaded functions in swift error.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With