Fizz Buzz
Here’s a simple “Fizz Buzz” example that prints “Fizz” when a given number is evenly divisible by 3, “Buzz” when it’s evenly divisible by 5, and “FizzBuzz” when it’s evenly divisible by both. Otherwise it prints the number.
for i in 1..16 {
print(
if i % 15 == 0 { "FizzBuzz" }
else if i % 3 == 0 { "Fizz" }
else if i % 5 == 0 { "Buzz" }
else { i }
)
}Press the play button to execute
The example shows how if/else-if/else can be used as an expression, not just a
statement. The result of the entire if-else chain is a value that’s passed as
the single argument to print. It also shows that the last expression in a block
like else { i } is the value of the block.