Adding Swift Closures as values to Swift dictionary

半腔热情 提交于 2019-12-08 17:19:05

问题


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.


回答1:


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



回答2:


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

        }
    }
}


来源:https://stackoverflow.com/questions/25068114/adding-swift-closures-as-values-to-swift-dictionary

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!