Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 532
Vik Singh Avatar asked Jul 31 '14 20:07

Vik Singh


People also ask

Can a closure be assigned to a variable Swift?

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.

How do I add a closure in Swift?

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.

How do you return a value from a closure in Swift?

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 ...).

Are closures value or reference types?

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.


2 Answers

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");

        }
    }
}
like image 75
Sandeep Avatar answered Sep 22 '22 23:09

Sandeep


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")
        }
    }
}
like image 27
Connor Avatar answered Sep 25 '22 23:09

Connor