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

swift – 不能下标'[String:String]类型的值?’索引类型为

发布时间:2020-12-14 05:26:53 所属栏目:百科 来源:网络整理
导读:let orch = NSUserDefaults().dictionaryForKey("orch_array")?[orchId] as? [String:String] orch[appleId] orch [appleId]行上的错误: Cannot subscript a value of type ‘[String : String]?’ with an index of type ‘String’ 为什么? 问题2: let
let orch = NSUserDefaults().dictionaryForKey("orch_array")?[orchId] as? [String:String]
   orch[appleId]

orch [appleId]行上的错误:

Cannot subscript a value of type ‘[String : String]?’ with an index
of type ‘String’

为什么?

问题2:

let orch = NSUserDefaults().dictionaryForKey("orch_array")?[orchId] as! [String:[String:String]]
   orch[appleId] = ["type":"fuji"]

错误:“无法分配此表达式的结果”

该错误是因为您尝试在可选值上使用下标.您正在转换为[String:String],但您正在使用转换运算符的条件形式(作为?).从文档:

This form of the operator will always return an optional value,and the value will be nil if the downcast was not possible. This enables you to check for a successful downcast.

因此,orch的类型为[String:String]?.要解决这个问题,您需要:

用作!如果你肯定知道返回的类型是[String:String]:

// You should check to see if a value exists for `orch_array` first.
if let dict: AnyObject = NSUserDefaults().dictionaryForKey("orch_array")?[orchId] {
    // Then force downcast.
    let orch = dict as! [String: String]
    orch[appleId] // No error
}

2.使用可选绑定检查orch是否为零:

if let orch = NSUserDefaults().dictionaryForKey("orch_array")?[orchId] as? [String: String] {
    orch[appleId] // No error
}

希望有所帮助.

(编辑:李大同)

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

    推荐文章
      热点阅读