The FizzBuzz Function
Part of the Fundamentals section of Coddy's Swift journey — lesson 59 of 86.
Challenge
EasyIn 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:
FizzBuzzIf the input is 4, the output should be:
4Try 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
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