UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Day 4: Skipping items - test: Redefining let constant explanation

Forums > 100 Days of Swift

Hi,

in "Skipping Items" test we have this code:

for i in 1...5 {
    if i == 5 {
        continue
    }
    let sum = i + i
    print("\(i) + \(i) is \(sum).")
}

, which is valid. I don't understand this part: "let sum = i + i", because I learned, that constant cannot be changed or defined again. Here we are definign constant with every round of loop and "sum" changing its value. So I'm confused, can you explain me please?

Thanks a lot.

3      

Hi, the thing here is "scope". The stuff inside for loop iteration is its own scope and goes away when the iteration ends. However inside the iteration scope you cannot redefine the constant.

This also means that sum is not available after the loop.

4      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.