Home > Software engineering >  Swift nested if else, making it better
Swift nested if else, making it better

Time:07-29

Hi my code is very inefficient which frustrates me, I don't know how to make it better. I am a beginner, does anyone have any suggestions for improvement?

The issue is that the length of questioncount is 12 and I want to increase the progressbar every time I go from page 1 to page 2 etc. until the last page 12 Is there any other possibility? Thanks for your time

var setProgress = questionCount
            print (setProgress)
            
            if setProgress == 1 {
                progressBar.setProgress(0.08, animated: true)
            } else if setProgress == 2{
                progressBar.setProgress(0.16, animated: true)
            } else if setProgress == 3{
                progressBar.setProgress(0.24, animated: true)
            } else if setProgress == 4{
                progressBar.setProgress(0.32, animated: true)
            } else if setProgress == 5{
                progressBar.setProgress(0.40, animated: true)
            } else if setProgress == 6{
                progressBar.setProgress(0.52, animated: true)
            } else if setProgress == 7{
                progressBar.setProgress(0.55, animated: true)
            } else if setProgress == 8{
                progressBar.setProgress(0.64, animated: true)
            } else if setProgress == 9{
                progressBar.setProgress(0.75, animated: true)
            } else if setProgress == 10 {
                progressBar.setProgress(0.88, animated: true)
            } else if setProgress == 11 {
                progressBar.setProgress(0.95, animated: true)
            } else {
                progressBar.setProgress(1, animated: true)
            }
            

CodePudding user response:

Since you have a small, contiguous range of valid integer questionCount values, you can create an array that indicates the progress bar's progress amount for each value of questionCount. The following code will handle all values of questionCount, make it easy to add or modify the progress amounts, and also gracefully handles unexpected values of setProgress:

let progressAmounts = [0, 0.08, 0.16, 0.24, 0.32, 0.40, 0.52, 0.55, 0.64, 0.75, 0.88, 0.95]

if progressAmounts.indices.contains(questionCount) {
    progressBar.setProgress(progressAmounts[questionCount], animated: true)
} else {
    progressBar.setProgress(1, animated: true)
}
  • Related