demonofthemist
demonofthemist

Reputation: 4199

Swift callback after object function

I have a Class to store user geo info & get locations etc. This class object is used in the my Home ViewController.

Example:

class Geo {

    ...
    getLocation()
    getRoute()
    ...

}

class ViewController {
    var geo = Geo()
    geo.getRoute()

    // I want a call a function after getRoute is complete.
}

One method which I know is using delegate, where my ViewController is delegate of the Geo class object. But is there any straight & simple method, cause any of methods of Geo object will be used by any controller in app.

Upvotes: 0

Views: 616

Answers (1)

Keiwan
Keiwan

Reputation: 8281

As has been suggested in the comments you can pass a function to getRoute to be called when it is completed. You would have to change the declaration of getRoute to something like

func getRoute(_ completionHandler: (() -> Void)?) {...}

and then at the end of the getRoute implementation call:

if let completion = completionHandler {
    completion()
}

and when you call getRoute you simply have to pass the function you want to be called as the last argument:

geo.getRoute() {
   // do something when getRoute is finished
}

Upvotes: 3

Related Questions