Adding The Twist
Part of the Fundamentals section of Coddy's Swift journey — lesson 61 of 86.
Challenge
EasyIn 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
fizzAtinstead of 3 for the "Fizz" check - Use
buzzAtinstead 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:
- The upper limit (integer)
- The first divisor for "Fizz" (integer)
- 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
FizzIn 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
FizzBuzzTry 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
4Operators Part 1
Arithmetic OperatorsModulo OperatorCompound AssignmentRecap - Simple MathComparison Operators7Basic IO
Print FunctionString InterpolationReadLine InputType ConversionRecap - Till 120Recap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesArgument LabelsRecap - Sigma FunctionRecap - Validation FunctionDefault Values13Iterating Over Sequences
Iterating Over ElementsThe Enumerated MethodIterating Over Strings P1Iterating Over Strings P22Variables
Let vs VarType AnnotationsNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Ternary Operator8Bill Split Calculator
Welcome MessageGetting Input3Optionals
What Are OptionalsUnwrapping With If LetGuard LetNil Coalescing OperatorRecap - Safe Unwrapping9Loops
For-In LoopWhile LoopRepeat-While LoopBreakContinueRecap - FactorialRanges In LoopsNested LoopRecap - Dynamic Input