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
Learn about control flow and scope in Swift 2 including making decisions, conditions and repeating steps with loops.
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:
backwards
is 10repeat
backwards
is now 10 - 1
or 9backwards > 0
backwards
is now 9 - 1
or 8etc.
Thatβs why the printing starts with β9β. Now if you swap lines 3 and 4β¦
backwards
is 10repeat
backwards
is now 10 - 1
or 9backwards > 0
backwards
is now 9 - 1
or 8etc.
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?