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

Commit 78aacfd

Browse files
rjzakrvolosatovs
authored andcommitted
fixup: Swift example takes arguments from CLI
Signed-off-by: Richard Zak <[email protected]>
1 parent c3e130e commit 78aacfd

File tree

1 file changed

+29
-10
lines changed

1 file changed

+29
-10
lines changed

Swift/fibonacci/fibonacci.swift

+29-10
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,31 @@
1-
func fibonacci(n: Int) -> Int {
2-
var a = 0
3-
var b = 1
4-
for _ in 0..<n {
5-
let temp = a
6-
a = b
7-
b = temp + b
8-
}
9-
return a
1+
func fib(n: UInt) -> UInt {
2+
if n <= 1 {
3+
return n
4+
}
5+
6+
return fib(n: n-1) + fib(n: n-2)
107
}
118

12-
print(fibonacci(n:7))
9+
let arguments = CommandLine.arguments
10+
11+
var n:UInt
12+
if (arguments.count > 1) {
13+
for i in 1...arguments.count-1 {
14+
if let n = UInt(arguments[i]) {
15+
print("Fibonacci sequence number at index \(n) is \(fib(n: n))")
16+
} else {
17+
print("Failed to parse argument into a number: \(arguments[i])\n")
18+
}
19+
}
20+
} else {
21+
print("Enter a non-negative number:")
22+
if let line = readLine() {
23+
if let n = UInt(line) {
24+
print("Fibonacci sequence number at index \(n) is \(fib(n: n))")
25+
} else {
26+
print("Could not convert \(line) to integer.\n")
27+
}
28+
} else {
29+
print("Could not read user input.\n")
30+
}
31+
}

0 commit comments

Comments
 (0)