Skip to content
This repository has been archived by the owner on Aug 27, 2024. It is now read-only.

Commit

Permalink
fixup: Swift example takes arguments from CLI
Browse files Browse the repository at this point in the history
Signed-off-by: Richard Zak <[email protected]>
  • Loading branch information
rjzak authored and rvolosatovs committed Aug 2, 2022
1 parent c3e130e commit 78aacfd
Showing 1 changed file with 29 additions and 10 deletions.
39 changes: 29 additions & 10 deletions Swift/fibonacci/fibonacci.swift
Original file line number Diff line number Diff line change
@@ -1,12 +1,31 @@
func fibonacci(n: Int) -> Int {
var a = 0
var b = 1
for _ in 0..<n {
let temp = a
a = b
b = temp + b
}
return a
func fib(n: UInt) -> UInt {
if n <= 1 {
return n
}

return fib(n: n-1) + fib(n: n-2)
}

print(fibonacci(n:7))
let arguments = CommandLine.arguments

var n:UInt
if (arguments.count > 1) {
for i in 1...arguments.count-1 {
if let n = UInt(arguments[i]) {
print("Fibonacci sequence number at index \(n) is \(fib(n: n))")
} else {
print("Failed to parse argument into a number: \(arguments[i])\n")
}
}
} else {
print("Enter a non-negative number:")
if let line = readLine() {
if let n = UInt(line) {
print("Fibonacci sequence number at index \(n) is \(fib(n: n))")
} else {
print("Could not convert \(line) to integer.\n")
}
} else {
print("Could not read user input.\n")
}
}

0 comments on commit 78aacfd

Please sign in to comment.