Day 4 – Loops

// for loops
let count = 1...3
for number in count {
    print("Number is \(number)")
}

let albums = ["Black Album", "White Album", "BOBD"]
for album in albums {
    print("\(album) is on Spotify")
}

// in case we don't want to use the value Swift gives us, like "album" or "number", we replace it with an underscore

for _ in 1...5 {
    print("Very cool.")
}

// while loops
var i = 1
//while i <= 20 {
//    i += 1
//}

// repeat loops

repeat {
    i += 1
} while i <= 20

// the difference is that in a repeat, the loop will be run at least once

// exiting loops
// the keyword "break" helps us out

var countdown = 10

while countdown >= 0 {
    if countdown == 4 {
        print("We're going boyyes")
        break
    }
   
    countdown -= 1
}

// breaking nested loops at the same time

for i in 1...10 {
    for j in 1...10 {
        let product = i*j
        print("\(i) * \(j) is \(product)")
    }
}

// here, we don't break out of anything. let's break both at the same time

outerLoop: for i in 1...10 { // labeling the outer loop
    for j in 1...10 {
        let product = i*j
        print("\(i) * \(j) is \(product)")
       
        if product == 50 {
            print("We're breaking outta here.")
            break outerLoop // breaking the outer loop as to break both
        }
    }
}

// skipping items with continue

for i in 1...10 {
    if i % 2 == 1 {
        continue
    }
    print(i)
}

// infinite loops

var counter = 0
while true {
    counter += 1
   
    print("Good luck getting out of this kiddo.")
   
    if counter == 4 {
        print("Eject!")
        break
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *