![swift – 不能下标'[String:String]类型的值?’索引类型为’String’,第1张 swift – 不能下标'[String:String]类型的值?’索引类型为’String’,第1张](/aiimages/swift+%E2%80%93+%E4%B8%8D%E8%83%BD%E4%B8%8B%E6%A0%87%26amp%3B%2339%3B%5BString%EF%BC%9AString%5D%E7%B1%BB%E5%9E%8B%E7%9A%84%E5%80%BC%EF%BC%9F%E2%80%99%E7%B4%A2%E5%BC%95%E7%B1%BB%E5%9E%8B%E4%B8%BA%E2%80%99String%E2%80%99.png)
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} 希望有所帮助.
总结以上是内存溢出为你收集整理的swift – 不能下标'[String:String]类型的值?’索引类型为’String’全部内容,希望文章能够帮你解决swift – 不能下标'[String:String]类型的值?’索引类型为’String’所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)