Introduction to Swift

Apr 24 2024 · Swift 5.10, iOS 17, Xcode 15

Lesson 02: Flow Control & Functions

Function Demo

Episode complete

Play next episode

Next

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

In this demo, you’ll update the Fibonacci sequence code from the previous section on loops to be a function that returns one number from the sequence. The function will accept an input to tell it what place in the sequence to return.

func getFibonacciElement() {

}
var fibonacciSeries: [Int] = []

for index in 0...10 {
  if index < 2 {
    fibonacciSeries.append(index)
  } else {
    let element1 = fibonacciSeries[fibonacciSeries.count-1]
    let element2 = fibonacciSeries[fibonacciSeries.count-2]
    fibonacciSeries.append(element1 + element2)
  }
}

print(fibonacciSeries)
func getFibonancciElement(at inputIndex: Int) {
getFibonacciElement(at: 5)
for index in 0...inputIndex
getFibonacciElement(at: 11)
func getFibonancciElement(at inputIndex: Int) -> Int {
return fibonacciSeries[inputIndex]
print(getFibonacciElement(at: 11))
print(getFibonacciElement(at: 5))
print(getFibonacciElement(at: 1))
print(getFibonacciElement(at: 0))
print(getFibonancciElement(at: -1))
if inputIndex < 0 {
  return 0
}
See forum comments
Cinema mode Download course materials from Github
Previous: Functions Next: Conclusion