tymac tymac - 3 months ago 8
Swift Question

How to write a condition which is based on calls from different external IBActions?

I have these two IBActions in WorkoutsController.swift.

@IBAction func startWalkingButton() {

print("Walking start button pressed")
presentControllerWithName("Dashboard", context: sessionContext)

wSM!.startWorkout()
}


@IBAction func startCyclingButton() {
print("Cycling start button pressed")
presentControllerWithName("Dashboard", context: sessionContext)

wSM!.startWorkout()
}


They are calling the
startWorkout()
function in WorkoutSessionManager.swift

func startWorkout() {
self.healthStore.startWorkoutSession(self.workoutSession)

if ... {
print("startWorkout() called from startWalkingButton")
} else if ... {
print("startWorkout() called from startCyclingButton")
}
}


How do I create a condition to print out different print statements depending on which button called the method? Should I use an if statement or switch statement?

I know there is already a print statement for the separate IBActions but I want to know if it's possible to do it in the reverse for redundancy.

Answer

Simply add one Bool parameter with your method startWorkout

func startWorkout(isFromWalking: Bool) {
    if (isFromWalking) {
        print("startWorkout() called from startWalkingButton")
    }
    else {
        print("startWorkout() called from startCyclingButton")
    }
}

Now call this function from startWalkingButton method with passing true

startWorkout(true)

and from startCyclingButton method with passing false

startWorkout(false)

Edit:

You haven't told that you have multiple option, then best option is to used enum in this case, create one enum like this and use that with the method

enum Workout  {
   case Walking
   case Cycling
   //Add case that you have
}

Now change the function like this 

func startWorkout(workout: Workout) {
    switch(workout) {
    case .Walking :
        print("Walking")
    case .Cycling:
        print("Cycling")
    }
}

And call the function like this

self.startWorkout(.Walking)
self.startWorkout(.Cycling)