Beginning Swift 3 - Part 6: If Statements | Ray Wenderlich

Learn about if statements in Swift 3.


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/4095-beginning-swift-3/lessons/6

A useful video, as always. The challenge code could use a review. I’m pretty sure a few bugs have creeped into the solution playground.

There are simple issues, like 18 that should be 19 for comparison, but there is a larger issue in that the brackets don’t make a lot of sense, especially when compared to the Switch statement brackets in that video’s challenge. I can suss out what you meant, but I suggest that the challenge could be improved with some light editing of the problem text and a review of the various comparisons.

Thanks for the heads up … we’ve recently incorporate tech editors into a video production schedule which will hopefully catch a lot of these types of errors.

You need to test out the solutions a little more. Try for instance setting your age to 19 and be dismayed to find you are a teenager and an Adult and in Middle Age…

Thanks for the heads up … traditionally, it’s been up to the instructor to provide challenge files and materials, but we found that was prone to error. We are now employing tech editors to review materials to catch these kind of bugs. That said, I appreciate you letting me know and I have updated the materials accordingly. Many thanks!

The video was useful and well explained.However, I didn’t understood the difference between else if and else.Also,can you
elaborate the overwriting thing you talked about in the video ?

Yet we have a solution, I think it’d be more elegant to do it the way below (assuming that we don’t know switch statement yet :slight_smile: ).

We can divide our ages into 3 general ranges:

  • younger than 13;

  • older than 19;

  • everybody else (teenagers).

    if myAge < 13 {
    print(“Pre teen”)
    if myAge >= 1 && myAge <= 4 {
    print (“Toddler”)
    } else {
    print(“Child”)
    }
    } else if myAge > 19 {
    print(“Adult”)
    if myAge >= 40 && myAge <= 65 {
    print(“Middle Age”)
    } else if myAge > 65 {
    print(“Senior Citizen”)
    }
    } else {
    print(“Teenager”)
    }

As you see, I didn’t specified conditions for Child range - it just comes from what’s left.

Pay attention that you can’t do this for Senior Citizen range. You have to explicitly tell “older than 65” (> 65) in the else if, otherwise you’ll get Senior citizens not only older than 65 but also in the range [20-39] years.

For teenagers we just use “else” (what’s left after we used <13 and > 19).