Skip to content

Instantly share code, notes, and snippets.

@L-A
Created October 6, 2017 01:36
Show Gist options
  • Save L-A/93e5f4b36dbc12621672c183562bf01a to your computer and use it in GitHub Desktop.
Save L-A/93e5f4b36dbc12621672c183562bf01a to your computer and use it in GitHub Desktop.
Fizz Buzz
func fizzBuzz (size: Int) {
// An array can be declared like this
var list: Array<Int> = []
// Alternatively, you can instantiate:
// var list = [Int]()
// This array creation is oddly slow in Playgrounds (try it with size: 400).
// Then again, I shouldn't need *two* loops for a fizzbuzz.
var i = 1
while (i <= size) {
list.append(i)
i += 1
}
// List iteration:
for val in list {
var output: String = ""
// Doing each comparison only once
let fizz = (val % 3 == 0)
let buzz = (val % 5 == 0)
// Convert an Int into a String explicitly
if (!fizz && !buzz) { output = String(val) }
// Implicitly, by escaping `val` in a composed string:
// output = "\(val)"
if (fizz) { output.append("fizz")}
if (buzz) { output.append("buzz")}
print(output)
}
}
fizzBuzz(size:100) // Or whatever
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment