From 8cb0a1a8012342e152d0b9f756e684da6bca747a Mon Sep 17 00:00:00 2001 From: Richard Zak Date: Thu, 28 Jul 2022 12:58:58 -0400 Subject: [PATCH] fixup: Swift example takes arguments from CLI Signed-off-by: Richard Zak --- Swift/fibonacci/fibonacci.swift | 39 ++++++++++++++++++++++++--------- 1 file changed, 29 insertions(+), 10 deletions(-) diff --git a/Swift/fibonacci/fibonacci.swift b/Swift/fibonacci/fibonacci.swift index 7e36bd9a..d03d5a0e 100644 --- a/Swift/fibonacci/fibonacci.swift +++ b/Swift/fibonacci/fibonacci.swift @@ -1,12 +1,31 @@ -func fibonacci(n: Int) -> Int { -var a = 0 -var b = 1 -for _ in 0.. 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("Which Fibonacci index to find? ") + 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") + } +}