Dak Song Dak Song - 5 months ago 28
iOS Question

Swift: Can you store functions as values in a dictionary?

I am learning Swift, and I was wondering if you could store functions as values in a dictionary. For example, a dictionary that would be something like a String mapped to a Function.

var test : Dictionary = [String : Double -> Double]()


I tried this, but the compiler didn't like it, saying it expected a ','. If creating such a dictionary is possible, how would I create it?

Answer

You could do something like this :) And compiler wont say a word :)

 typealias myFunc = (Double) -> Double
var test3 : [String : myFunc] = [String : myFunc]()

OR

typealias myFunc = (Double) -> Double
var test3 : Dictionary = [String : myFunc]()

Finally this is how you can add one to dictionary :)

let mtfunc : myFunc =  {
     print("Hi")
     return $0
}

test3["Sandeep"] = mtfunc