TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to SWIFT

Swift Fibonacci Numbers

Implement the Fibonacci method. Use an iterative version in a for-loop.
Fibonacci. This is an important numeric sequence. In the Fibonacci sequence, each number is the sum of the two previous numbers. This sequence is found in many parts of our world.
With iteration, we can efficient compute this sequence. There is no reason to use recursion (except for education purposes—to learn). In this example we use a simple for-loop with ranges.
Example code. Let us begin. We introduce fibonacci(), which receives one Int and returns another. We use three temporary variables. We use an implicit local constant "_" in our for-loop.

Half-open range: Our for-loop uses a half-open range. So it loops from 0 to one minus the final number "n." This is a useful syntax form.

Range

Temp: We use a temporary constant with the let keyword. This is how we swap the two numbers.

Swift program that implements Fibonacci method func fibonacci(n: Int) -> Int { // Some temporary variables. var a = 0 var b = 1 // Add up numbers to the desired iteration. for _ in 0..<n { let temp = a a = b b = temp + b } return a } // Loop over values 0 through 14 inclusive. for i in 0..<15 { // Call Fibonacci method. let result = fibonacci(i) print("Fibonacci \(i) = \(result)") } Output Fibonacci 0 = 0 Fibonacci 1 = 1 Fibonacci 2 = 1 Fibonacci 3 = 2 Fibonacci 4 = 3 Fibonacci 5 = 5 Fibonacci 6 = 8 Fibonacci 7 = 13 Fibonacci 8 = 21 Fibonacci 9 = 34 Fibonacci 10 = 55 Fibonacci 11 = 89 Fibonacci 12 = 144 Fibonacci 13 = 233 Fibonacci 14 = 377
Some notes. The Fibonacci sequence is important. Even in stock trading, investors may use Fibonacci numbers to try to lose even greater amounts of money. Wikipedia has more details.Fibonacci number: WikipediaFibonacci retracement: Wikipedia
A review. With a simple iterative method, we can quickly compute Fibonacci numbers. Storing these in another Swift data structure like an array can help retrieve these values faster.Array
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf