functional-programmingswift2xcode7-beta6

Passing a Closure as an Argument to another Function won't work


I have a function evaluate that takes arguments. The first argument is an Int. The second argument of a closure that takes an Int and returns a Double. The function evaluate then returns a [Double]. The k’th element of the returned array is the result of evaluating the second argument with the value k for k = 0, 1, ..., n.

func evaluate(n: Int, myFunction: Int -> Double) -> [Double] {
    var doubles = [Double]()
    for i in 1...n {
        doubles[i] = myFunction(i)
    }

    return doubles
}

let polyTableClosure: Int -> Double = { return Double($0 * $0 * $0 + 2 * $0 + 4) }

print(evaluate(5, polyTableClosure))

Expecting something like: [7, 16, 37, 76, 139]


Solution

  • The myFunction: label is missing. Your call of evaluate should be:

    evaluate(5, myFunction: polyTableClosure)
    

    Also, accessing an empty array at index i will not create a new slot at that index. It will fail.

    You must append to the array:

    for i in 1...n {
        doubles.append(myFunction(i))
    }