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],但您正在使用转换运算符的条件形式(作为?).从文档:
原文链接:https://www.f2er.com/swift/319216.htmlThis 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 }
希望有所帮助.