Menu
Coddy logo textTech

The FizzBuzz Function

Part of the Fundamentals section of Coddy's Swift journey — lesson 59 of 86.

challenge icon

Challenge

Easy

In the previous lesson, you wrote code to check a single number against FizzBuzz rules. Now, refactor that logic into a reusable function.

Create a function called fizzBuzz that takes a number and returns the appropriate string based on the FizzBuzz rules:

  • If the number is divisible by both 3 and 5, return "FizzBuzz"
  • If the number is divisible by 3 only, return "Fizz"
  • If the number is divisible by 5 only, return "Buzz"
  • Otherwise, return the number as a string

Function signature:

  • Name: fizzBuzz
  • Parameter: number (Int) - use _ to omit the argument label
  • Returns: String

After defining the function, read a single integer from input, call your fizzBuzz function with that value, and print the result.

You will receive the following input:

  • A single integer

For example, if the input is 15, the output should be:

FizzBuzz

If the input is 4, the output should be:

4

Try it yourself

// Read input
let number = Int(readLine()!)!

// TODO: Write your code below to implement FizzBuzz logic
// Check divisibility by 3 and 5, then print the appropriate result
if number % 3 == 0 && number % 5 == 0 {
    print("FizzBuzz")
} else if number % 3 == 0 {
    print("Fizz")
} else if number % 5 == 0 {
    print("Buzz")
} else {
    print(number)
}

All lessons in Fundamentals