user2727195
user2727195

Reputation: 7330

Closures in dictionaries

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

Error

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

Answers (1)

drewag
drewag

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

Related Questions