1

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]

Xavjer
  • 8,838
  • 2
  • 22
  • 42

1 Answers1

2

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))
}
Mario Zannone
  • 2,843
  • 12
  • 18
  • yeah the problem is {doubles[i] = myFunction(i)}. I don't have to explicitly do it this way {evaluate(5, myFunction: polyTableClosure)}. This is {print(evaluate(5, polyTableClosure))} just working fine. Thanks a lot!!! I was pulling my hair for an hour on this. – Kranthi Kumar Gurrala Sep 04 '15 at 09:38