Vik Singh Vik Singh - 1 month ago 6
iOS Question

Adding Swift Closures as values to Swift dictionary

I want to create a Swift dictionary that holds String type as its keys and Closures as its values. Following is the code that I have but it gives me the error:

'@lvalue is not identical to '(String, () -> Void)'

class CommandResolver {
private var commandDict:[String : () -> Void]!

init() {
self.setUpCommandDict();
}

func setUpCommandDict() {

self.commandDict["OpenAssessment_1"] = {
println("I am inside closure");

}
}
}


I tried looking at other question on StackOverflow regarding closures in dictionaries but it does not give me any satisfactory answer. So I would really appreciate some help here.

Answer

If you initialize your dictionary in your init before calling your setup function, it should work:

class CommandResolver {
    private var commandDict: [String: () -> Void]

    init() {
        commandDict = [:]
        setUpCommandDict()
    }

    func setUpCommandDict() {
        commandDict["OpenAssessment_1"] = {
            println("I am inside closure")
        }
    }
}
Comments