本文介绍了将Swift Closures作为值添加到Swift字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建一个Swift字典,它包含String类型作为其键和Closures作为其值。下面是我的代码,但它给我的错误:
'@ lvalue不等于'(String,() - > Void)'
class CommandResolver {
private var commandDict:[String:() - >空虚]!
init(){
self.setUpCommandDict();
}
func setUpCommandDict(){
self.commandDict [OpenAssessment_1] = {
println(I am inside inside closure);
}
}
}
看看关于StackOverflow关于字典中的闭包的其他问题,但它不给我任何满意的答案。
解决方案
如果你在 init
在调用你的设置函数之前,它应该工作:
class CommandResolver {
/ pre>
private var commandDict: [String:() - > Void]
init(){
commandDict = [:]
setUpCommandDict()
}
func setUpCommandDict(){
commandDict [OpenAssessment_1] = {
println(I am inside closure)
}
}
}
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.
解决方案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") } } }
这篇关于将Swift Closures作为值添加到Swift字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!