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.
Closures are self-contained blocks of functionality that can be passed around and used in your code. Said differently, a closure is a block of code that you can assign to a variable. You can then pass it around in your code, for instance to another function.
Closures as Function Parameter In Swift, we can create a function that accepts closure as its parameter. Here, search - function parameter. () -> () - represents the type of the closure.
Instead, in the closure, take the return value that you want in the cell and store it somewhere (in a member variable) and have the tableView update it itself (e.g. with tableView. reloadData() ). This will cause it to get the cell again (cellForRow ...).
Closures Are Reference Types Whenever you assign a function or a closure to a constant or a variable, you are actually setting that constant or variable to be a reference to the function or closure.
Here is the way to go. I am not sure exactly why your implementation does not work though.
class CommandResolver {
typealias MyBlock = () -> Void
private var commandDict:[String : MyBlock] = [String:MyBlock]()
init() {
self.setUpCommandDict();
}
func setUpCommandDict() {
self.commandDict["OpenAssessment_1"] = {
print("I am inside closure");
}
}
}
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")
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With