## SOLVED: Day 6 Challenge

 Mar '23 This was fun but I'm wondering if there is always more than 1 way to solve a problem, and if so what makes 1 version better or worse? My solution was to use a while loop.... please feel free to leave me a comment as this is my first time learning any coding language so encouragement and pointers are welcomed. ``````var number = 1 while number <= 100 { //check for multiple of 3 and 5 if number % 3 == 0 && number % 5 == 0 { print("FizzBuzz") } //check for multiple of 3 else if number % 3 == 0 { print("Fizz") } //check for multiple of 5 else if number % 5 == 0 { print("Buzz") } // or just print the number else { print("\(number)") } number += 1 }`````` Mar '23 In Swift, you should really use `isMultiple(of:)` instead of the remainder operator `%`. It reads better and it functions better on certain edge cases. Which is easier to understand? ``````if number % 3 == 0 && number % 5 == 0 { print("FizzBuzz") }`````` or: ``````if number.isMultiple(of: 3) && number.isMultiple(of: 5) { print("FizzBuzz") }`````` 1 Mar '23 `while` tends to be used for indeterminate conditions (that is conditionals where you are not certain exactly when they will become false). For ranges it is better to use `for … in …` ``````for number in 1...100 { var result = "" if number.isMultiple(of: 3) { result += "Fizz" } if number.isMultiple(of: 5) { result += "Buzz" } if result.isEmpty { result = String(number) } print(result) }`````` A bit less readble, but they do the same job, and are a variations on a theme using combinations of ternaries ``````for number in 1...100 { number.isMultiple(of: 3) ? (number.isMultiple(of: 5) ? print("FizzBuzz") : print("Fizz")) : number.isMultiple(of: 5) ? print("Buzz") : print(String(number)) }`````` ``````for number in 1...100 { var result = "" result = number.isMultiple(of: 3) ? (number.isMultiple(of: 5) ? "FizzBuzz" : "Fizz") : number.isMultiple(of: 5) ? "Buzz" : String(number) print(result) }`````` ``````for number in 1...100 { print (number.isMultiple(of: 3) ? (number.isMultiple(of: 5) ? "FizzBuzz" : "Fizz") : number.isMultiple(of: 5) ? "Buzz" : String(number)) }`````` Mar '23 @roosterboy thank you, somehow I found the `%` before I found the `isMultiple(of: )` and yes it is much easier to read. @Greenamberred `while` felt familiar to me as I have used this function in filemaker but as you point out using `for … in …` is more appropriate. Thank you both for taking the time to help out

SPONSORED Let’s face it, SwiftUI previews are limited, slow, and painful. Judo takes a different approach to building visually—think Interface Builder for SwiftUI. Build your interface in a completely visual canvas, then drag and drop into your Xcode project and wire up button clicks to custom code. Download the Mac App and start your free trial today!

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