Closing in dictionaries
There is a question already posted with the accepted answer, but it is not working as of today. It throws an error in the PlaygroundExpected',' separator
Adding Swift Closures as Values to a Swift Dictionary
class CommandResolver {
private var commandDict: [String: () -> Void]
init() {
commandDict = [String: () -> Void]()
setUpCommandDict()
}
func setUpCommandDict() {
commandDict["OpenAssessment_1"] = {
println("I am inside closure")
}
}
}
+3
source to share
1 answer
This is most likely a compiler error. However, there is no need to change the type when creating an empty word. Instead, you can simply use an empty word literal:
init() {
self.commandDict = [:]
self.setUpCommandDict()
}
The dictionary type is inferred from the declaration commandDict
.
Another solution that I have used in the past is to use typealias
:
class CommandResolver {
typealias CallbackType = () -> Void
private var commandDict: [String: CallbackType]
init() {
self.commandDict = [String: CallbackType]()
self.setUpCommandDict()
}
func setUpCommandDict() {
self.commandDict["OpenAssessment_1"] = {
println("I am inside closure")
}
}
}
+5
source to share