Swift Tutorial Part 3: Flow Control | raywenderlich.com

Welcome to part 3 of our Swift tutorial, where you’ll learn how code decisions using Booleans and repeat tasks using loops to control the flow.


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/6366-swift-tutorial-part-3-flow-control

lorenzo you need to explain better as i cannnoot understand and i is 8

Hi Thomas, could you tell me which part / code snippet is not clear?

Thanks, Lorenzo

hi again borat, this just as confusing as the other one

@anthonybigdawg Please let me know what don’t you understand exactly when you get a chance. Thank you!

count = 10
sum = 1
var lastSum = 0

for _ in 0…<count {
let temp = sum
sum = sum + lastSum
lastSum = temp
}

This code will iterate 10 times (from 0 to 9)
But what is the code doing, exactly?

The variable ‘sum’ starts at ‘1’ and the range starts at ‘0’. This is what I’m getting:

sum = 1 + 0
sum = 1 + 1
sum = 2 + 2
sum = 4 + 3
sum = 7 + 4
sum = 11 + 5
sum = 16 + 6
sum = 22 + 7
sum = 29 + 8
sum = 37 + 9

I know it’s wrong, because the result gives 55. Can you please explain the above code in words?

@triplespace You can get the sum of all digits with the following code snippet:

var sum = 0
for digit in 1...9 {
  sum += digit
}

Please let me know if you have any questions or issues about the whole thing.

Thank you!

Thank you. I can understand the code you provided, it’s much more straightforward.

I just want to make sure I’m not missing anything with the other code. Trying to get the basics down.

What is the other code saying?

“In the range 0 to 9, the constant ‘temp’ = ‘sum.’
‘sum’ = its own value + ‘lastSum.’
‘lastSum’ = ‘temp’”

The first iteration is?
temp = 1
sum = 1 + lastSum
lastSum = 1

temp = ??

I think the order is confusing me.

Thanks for your help.

This tutorial is more than six months old so questions are no longer supported at the moment for it. Thank you!