Feature Map in Swift

Is it possible to have a map String:Function

in Swift?

Something like this (which doesn't work):

let map = [
    "action": func() { print("action!") },
    "error": func() {print("error!") }
]

      

What are other design patterns that I can follow to achieve this?

+3


source to share


1 answer


You can do this by setting a closure in the dictionary

let map = [
    "action": {() in print("action!") },
    "error":  {() in print("error!") }
]

      

or by creating functions outside of the dictionary and giving them names and then passing those names to the dictionary



func action() {
    print("action!")
}

func error() {
    print("error!")
}

let map = [
    "action": action,
    "error": error
]

      

It looks like you want an unnamed anonymous function (or closure), which is what the first solution gives. The keyword func

can only be used to create named functions.

+6


source







All Articles