Kodeco Forums

Video Tutorial: Beginning Swift 2 Part 3: Control Flow & Scope

Learn about control flow and scope in Swift 2 including making decisions, conditions and repeating steps with loops.


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/3250-beginning-swift-2/lessons/4

Hey there,

Thanks for the video. I did the last repeat/while challenge and noticed something odd.

This was my code

var backwards = 10
repeat {
    backwards = backwards - 1
    print("backwards is: \(backwards)")
} while backwards > 0

Output:

backwards: 9
backwards: 8
backwards: 7
backwards: 6
backwards: 5
backwards: 4
backwards: 3
backwards: 2
backwards: 1
backwards: 0

I was wondering why I was not getting the 10 inclusive. I looked at your answers and the only difference I saw was that you declared the print statement before the backCounter assignment. Why does that matter?

Hi @pinar747, try reading the code step-by-step as if you were the compiler (or an interpreter) and I hope you’ll see the difference:

  1. backwards is 10
  2. Start the loop with repeat
  3. backwards is now 10 - 1 or 9
  4. Print out 9
  5. Go back to line 2 if backwards > 0
  6. backwards is now 9 - 1 or 8
  7. Print out 8

etc.

That’s why the printing starts with β€œ9”. Now if you swap lines 3 and 4…

  1. backwards is 10
  2. Start the loop with repeat
  3. Print out 10
  4. backwards is now 10 - 1 or 9
  5. Go back to line 2 if backwards > 0
  6. Print out 9
  7. backwards is now 9 - 1 or 8

etc.

I hope that helps and makes sense! Thanks for your questions and I hope you enjoy the videos.

Hi, I have a question regarding the challenge. This bit was pretty straighforward:

if totalBill > 50 && tipPercentage > 0.15 {
  print("That was an expensive, but good meal!")
}

// This prints the sentence.

However, I noticed that tipPercentage was never set before, only declared. As a matter of fact, if you try to get its value on its own, you get nothing. Also if you change the condition to just

if tipPercentage > 0.15 {

you get an error because tipPercentage has not been initialized.

If the logical && only evaluates to true when BOTH conditions are true, how come this evaluates to true if the value for second condition has not been set?