At this point you should be fairly comfortable with data types, conditions, loops, functions, and more, so your first challenge is to complete the Fizz Buzz test. This is a famous test commonly used to root out bad programmers during job interviews, and it goes like this:
To solve this challenge you’ll need to use quite a few skills you learned in this tutorial:
fizzbuzz()
. It should accept an Int
parameter, and return a String
.if
and else if
conditions to check the input number.%
, to check for even division. You’ll also need to use &&
to check for two things at once, because “Fizz Buzz” should only be printed if the input number is evenly divisible by 3 and 5.Here are some test cases for you to use:
fizzbuzz(number: 3)
fizzbuzz(number: 5)
fizzbuzz(number: 15)
fizzbuzz(number: 16)
When your code is complete, that code should produce “Fizz”, “Buzz”, “Fizz Buzz” and “16”.
Please try to code your answer now. I’ve written my own solution below to get you started, but it will help you internalize Swift better if you try writing your own code first. Remember: there is no learning without struggle, so you should just try – don’t worry if you have a hard time or don’t manage to finish.
If you’re finding it hard, here are some hints. I suggest you read these only if you really need them, and even then only read one at a time – you should try to solve the challenge while reading as few hints as possible!
func fizzbuzz(number: Int) -> String {
. That is, it should accept an integer and return a string.return
keyword, e.g. return “Fizz”
.if number % 3 == 0
.if number % 3 == 0 && number % 5 == 0
.OK, that’s it for hints. Below is my solution:
func fizzbuzz(number: Int) -> String {
if number % 3 == 0 && number % 5 == 0 {
return "Fizz Buzz"
} else if number % 3 == 0 {
return "Fizz"
} else if number % 5 == 0 {
return "Buzz"
} else {
return String(number)
}
}
SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.