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

fixup: Swift example takes arguments from CLI #26

Merged
merged 1 commit into from
Aug 2, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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")
}
}