Reputation: 7330
There's a question already posted with an accepted answer but as of today it's not working. It's throwing an error in Playground Expected',' separator
Adding Swift Closures as values to Swift dictionary
class CommandResolver {
private var commandDict: [String: () -> Void]
init() {
commandDict = [String: () -> Void]()
setUpCommandDict()
}
func setUpCommandDict() {
commandDict["OpenAssessment_1"] = {
println("I am inside closure")
}
}
}
Upvotes: 3
Views: 982
Reputation: 94723
This is a most likely a bug in the compiler. However, there is no need to respecify the type when creating the empty dictionary. Instead, you can just use an empty dictionary literal:
init() {
self.commandDict = [:]
self.setUpCommandDict()
}
The type for the dictionary is inferred from the commandDict
declaration.
The other solution I have used in the past is to use a 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")
}
}
}
Upvotes: 5