Fibonacci in Swift

So, I didn’t really need another distraction, but Swift has an interactive environment, so now I’m playing. Here are two functions for Fibonacci, first an iterative one, and then a recursive one.

Here’s the iterative version:

func fibonacciI(n: Int) {
    var f1=1, f2=1, fib=0
    for i in 3...n {
        fib = f1 + f2
        print("Fibonacci: \(i) = \(fib)")
        f1 = f2
        f2 = fib
    }
}

And now the recursive version:

func fibonacciR(n: Int) -> Int {
    if (n == 0){
        return 0
    } else if (n == 1) {
        return 1
    }
    return fibonacciR(n-1) + fibonacciR(n-2)
}

And now the version using arrays:

func fibonacciA(n: Int) {
    var fib: [Int] = []
    fib.append(1)
    fib.append(1)
    for i in 2..<n {
        fib.append(fib[i-1]+fib[i-2])
    }
    for i in 0..<n {
        print("\(fib[i])")
    }
}

Nothing terribly different about these implementations from other languages.  I do like the way it is possible to create an array and then append items to it. The range constraints in loops, i.e. and ..< are kind of interesting as well.

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s