Menu
Coddy logo textTech

Adding The Twist

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

challenge icon

Challenge

Easy

In the previous lesson, you created a loop that runs FizzBuzz from 1 to a given limit using the fixed divisors 3 and 5. Now, add the twist by making the divisors customizable!

Modify your fizzBuzz function to accept two additional parameters for the custom divisors:

  • Update the function signature to: fizzBuzz(_ number: Int, fizzAt: Int = 3, buzzAt: Int = 5) -> String
  • Use fizzAt instead of 3 for the "Fizz" check
  • Use buzzAt instead of 5 for the "Buzz" check
  • The default values ensure the classic FizzBuzz still works when divisors aren't specified

You will receive the following inputs:

  1. The upper limit (integer)
  2. The first divisor for "Fizz" (integer)
  3. The second divisor for "Buzz" (integer)

Update your loop to pass these custom divisors to the function for each number.

For example, if the inputs are 10, 2, and 3, the output should be:

1
Fizz
Buzz
Fizz
5
FizzBuzz
7
Fizz
Buzz
Fizz

In this example, "Fizz" prints for multiples of 2, "Buzz" for multiples of 3, and "FizzBuzz" for multiples of both (like 6).

If the inputs are 15, 3, and 5 (the classic divisors), the output should match the original FizzBuzz:

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

Try it yourself

func fizzBuzz(_ number: Int) -> String {
    if number % 3 == 0 && number % 5 == 0 {
        return "FizzBuzz"
    } else if number % 3 == 0 {
        return "Fizz"
    } else if number % 5 == 0 {
        return "Buzz"
    } else {
        return String(number)
    }
}

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

// Loop from 1 to limit and print the result for each number
for number in 1...limit {
    print(fizzBuzz(number))
}

All lessons in Fundamentals