Checkpoint 3

ยท

Loop through a range of 1 to 100 inclusive and write:

  • fizz for multiples of 3
  • buzz for multiples of 5
  • fizzbuzz for multiples of 3 and 5
  • otherwise just print the number
// attempt 1

for i in 1...100 {
    switch i {
        case i % 5 == 0 && i % 3 == 0:
            print("fizzbuzz")
        case i % 5:
            print("buzz")
        case i % 3:
            print("fizz")
        default:
            print("\(i)") 
    }
}

// result: Swift didn't like me doing it like this
// attempt 2
for i in 1...100 {

   var divisibleByFiveAndThree: Bool = (i % 3 == 0 && i % 5 == 0)
   var divisibleByFive: Bool = i % 5 == 0
   var divisibleByThree: Bool = i % 3 == 0

   if divisibleByFiveAndThree {
      print("fizzbuzz")
   } else if divisibleByFive {
      print("buzz")
   } else if divisibleByThree {
      print("fizz")
   } else {
      print("\(i)")
   }
}

// result: This worked, as expected. I was just trying to avoid using an if...else if control block
// attempt 3: Ternary?

for i in 1...100 {
   var divisibleByFiveAndThree: Bool = (i % 3 == 0 && i % 5 == 0)
   var divisibleByFive: Bool = i % 5 == 0
   var divisibleByThree: Bool = i % 3 == 0

    print(divisibleByFiveAndThree ? "fizzbuzz" : divisibleByFive ? "buzz" : divisibleByThree ? "fizz" : "\(i)")

}

// result: This absolutely worked and as a dev the one liner is ๐Ÿ”ฅ๐Ÿš€
But depending on the problem we are trying to solve, this may not be the most readable.

Note: I didn’t bother with reading the hints, but a good tip was to use the isMultiple(of: n)

Onward.

Currently
Building

1 product