C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Half-open range: Our for-loop uses a half-open range. So it loops from 0 to one minus the final number "n." This is a useful syntax form.
RangeTemp: We use a temporary constant with the let keyword. This is how we swap the two numbers.
Swift program that implements Fibonacci method
func fibonacci(n: Int) -> Int {
// Some temporary variables.
var a = 0
var b = 1
// Add up numbers to the desired iteration.
for _ in 0..<n {
let temp = a
a = b
b = temp + b
}
return a
}
// Loop over values 0 through 14 inclusive.
for i in 0..<15 {
// Call Fibonacci method.
let result = fibonacci(i)
print("Fibonacci \(i) = \(result)")
}
Output
Fibonacci 0 = 0
Fibonacci 1 = 1
Fibonacci 2 = 1
Fibonacci 3 = 2
Fibonacci 4 = 3
Fibonacci 5 = 5
Fibonacci 6 = 8
Fibonacci 7 = 13
Fibonacci 8 = 21
Fibonacci 9 = 34
Fibonacci 10 = 55
Fibonacci 11 = 89
Fibonacci 12 = 144
Fibonacci 13 = 233
Fibonacci 14 = 377