Group Group Group Group Group Group Group Group Group

Part 9: Adding Polish


#1

Welcome, this is a thread for collaboration, questions, and feedback on Part 9 of the iOS Apprentice Email course.

Bonus Points Challenge Solution

Here is how I would have made these changes:

@IBAction func showAlert() {
  let difference = abs(targetValue - currentValue)
  var points = 100 - difference     // change let to var

  let title: String
  if difference == 0 {
    title = "Perfect!"
    points += 100                   // add this line
  } else if difference < 5 {
    title = "You almost had it!"
    if difference == 1 {            // add these lines
      points += 50
    }	
  } else if difference < 10 {
    title = "Pretty good!"
  } else {
    title = "Not even close..."
  }
  score += points                   // move this line here
  . . .
}

You should notice a few things:

  • In the first if you’ll see a new statement between the curly brackets. When the difference is equal to zero, you now not only set title to “Perfect!” but also award an extra 100 points.

  • The second if has changed too. There is now an if inside another if. Nothing wrong with that! You want to handle the case where difference is 1 in order to give the player bonus points. That happens inside the new if statement.

    After all, if the difference is more than 0 but less than 5, it could be 1 (but not necessarily all the time). Therefore, you perform an additional check to see if the difference truly was 1, and if so, add 50 extra points.

  • Because these new if statements add extra points, points can no longer be a constant; it now needs to be a variable. That’s why you changed it from let to var.

  • Finally, the line score += points has moved below the ifs. This is necessary because the app updates the points variable inside those if statements (if the conditions are right) and you want those additional points to count towards the final score.

If your code is slightly different, then that’s fine too, as long as it works! There is often more than one way to program something, and if the results are the same, then any approach is equally valid.

Downloads

Here’s a download for the project to use at the beginning of this email:

BullsEye-part8-final-v2.zip (29.1 KB)

Here’s a download for the project where it stands at the end of this email:

BullsEye-part9-final-v2.zip (29.4 KB)