make a function that returns n first fibonacci numbers in swift

Here's a function that takes an input n and returns an array of the first n Fibonacci numbers in Swift:

main.swift
func fibonacci(_ n: Int) -> [Int] {
    guard n > 0 else {
        return []
    }
    var result = [0, 1]
    if n == 1 {
        return [0]
    } else if n == 2 {
        return result
    } else {
        for _ in 2..<n {
            let fibNumber = result[result.count - 1] + result[result.count - 2]
            result.append(fibNumber)
        }
        return result
    }
}
382 chars
18 lines

The function first checks to make sure that n is greater than 0. If it is not, it returns an empty array. If n is 1, it returns an array containing only 0. If n is 2, it returns an array containing [0, 1] (these are the first two Fibonacci numbers).

If n is greater than 2, the function uses a for loop to iterate from 2 up to n, and calculates each Fibonacci number by adding together the previous two numbers in the result array. Each new Fibonacci number is added to the result array using the append method. Finally, the result array is returned.

gistlibby LogSnag