This repository has been archived by the owner on Aug 27, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 14
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fixup: Swift example takes arguments from CLI
Signed-off-by: Richard Zak <[email protected]>
- Loading branch information
1 parent
c3e130e
commit 78aacfd
Showing
1 changed file
with
29 additions
and
10 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") | ||
} | ||
} |