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

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
}

希望有所帮助.

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...