Oscar Apeland Oscar Apeland - 6 months ago 9
Swift Question

Call different functions depending on a parameter

I'm rewriting some code, and trying to make a function less nested. The function takes an enum as an argument and does a

switch
on it. This is okay, but it adds two levels of indentation.

What I'd like to do, is something like this:

func getTrips<T : TripStatus.Confirmed> (status:T) {
//Do one thing
}

func getTrips<T : TripStatus.Unconfirmed> (status:T) {
//Do another thing
}


The enum is defined like:

enum TripStatus:String {
case Confirmed = "Confirmed", Unconfirmed = "Unconfirmed", Tracking = "Tracking", Empty = "Empty"
}


The goal is that I can just call
getTrips(status)
and Swift picks the correct function based on the enum value.

Answer

You could add a computed property to your TripStatus returning the function you want to execute based on the status and then call that. For example (in the example I return an optional function):

enum TripStatus: String {
    case Confirmed = "Confirmed", Unconfirmed = "Unconfirmed", Tracking = "Tracking", Empty = "Empty"

    var getTrips : (() -> ())? {
        switch self {
            case .Confirmed:    return self.getConfirmedTrips
            case .Unconfirmed:  return self.getUnconfirmedTrips
            default:            return nil
        }
    }

    func getConfirmedTrips() { print("getConfirmedTrips") }
    func getUnconfirmedTrips() { print("getConfirmedTrips") }
}

let status = TripStatus.Confirmed

status.getTrips?() // prints getConfirmedTrips