Search code examples
iosswiftxcodepolymorphismclosures

How To Store Swift function in a variable


// Assume you have two functions.
// Swift considers these functions as distinct
func cars(left look: String) {}
func cars(right look: String) {}

// How can I store them in a variable for later use?
let c: (left : String) -> ()  = cars
let c2: (right : String) -> () = cars

When I try to store these methods into a variable, I get an error stating that "cars" is ambiguous. What can I do to differentiate them?


Solution

  • You have to help the compiler decide which function you want because it does not distinguish between parameter names when deciding if a function's signature is valid for assignment.

    You can disambiguate your intent by being specific on the parameter names

    let c:  (left :String) -> () = cars(left:)
    let c2: (right:String) -> () = cars(right:)