加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

是否可以将带有可变数组的字典作为Swift中的值

发布时间:2020-12-14 05:24:58 所属栏目:百科 来源:网络整理
导读:我想这样做: var dictArray = [String:[String]]()dictArray["test"] = [String]()dictArray["test"]! += "hello" 但我得到了奇怪的错误NSString不是’DictionaryIndex String,[(String)]‘的子类型. 我只是希望能够将对象添加到字典中的数组中. 更新:看起
我想这样做:
var dictArray = [String:[String]]()
dictArray["test"] = [String]()
dictArray["test"]! += "hello"

但我得到了奇怪的错误NSString不是’DictionaryIndex< String,[(String)]>‘的子类型.

我只是希望能够将对象添加到字典中的数组中.

更新:看起来Apple认为这是Swift中的“已知问题”,暗示它最终将按预期工作.来自Xcode 6 Beta 4发行说明:

…Similarly,you cannot modify the underlying value of a mutable
optional value,either conditionally or within a force-unwrap:

06001

Workaround: Test the optional value explicitly and then assign the
result back:

06002

你只能这样做
var dictArray = [String:[String]]()
dictArray["test"] = [String]()
var arr = dictArray["test"]!;
arr += "hello"
dictArray["test"] = arr

因为dictArray [“test”]给你Optional< [String]>这是不可改变的

6> var test : [String]? = [String]()
test: [String]? = 0 values
  7> test += "hello"
<REPL>:7:1: error: '[String]?' is not identical to 'UInt8'

由于同样的原因,append也不会工作,Optional是不可变的

3> dictArray["test"]!.append("hello")
<REPL>:3:18: error: '(String,[(String)])' does not have a member named 'append'
dictArray["test"]!.append("hello")
                 ^ ~~~~~~

BTW错误信息很可怕……

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读