将Swift Closures作为值添加到Swift字典

编程入门 行业动态 更新时间:2024-10-25 12:17:53
本文介绍了将Swift Closures作为值添加到Swift字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想创建一个Swift字典,它包含String类型作为其键和Closures作为其值。下面是我的代码,但它给我的错误:

'@ lvalue不等于'(String,() - > Void)'

class CommandResolver { private var commandDict:[String:() - >空虚]! init(){ self.setUpCommandDict(); } func setUpCommandDict(){ selfmandDict [OpenAssessment_1] = { println(I am inside inside closure); } } }

看看关于StackOverflow关于字典中的闭包的其他问题,但它不给我任何满意的答案。

解决方案

如果你在 init 在调用你的设置函数之前,它应该工作:

class CommandResolver { private var commandDict: [String:() - > Void] init(){ commandDict = [:] setUpCommandDict()} func setUpCommandDict(){ commandDict [OpenAssessment_1] = { println(I am inside closure)} } } / pre>

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() { selfmandDict["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字典

本文发布于:2023-11-26 03:17:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1632416.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字典   Swift   Closures

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!