gpt4 book ai didi

swift - 无法使用类型为 '[String : String]?' 的索引下标类型为 'String' 的值

转载 作者:IT王子 更新时间:2023-10-29 05:46:54 24 4
gpt4 key购买 nike

   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] 但您使用的是转换运算符的条件形式 (as?)。来自文档:

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]? 类型。要解决这个问题,您需要:

1. 如果您确定返回的类型是 [String: String],请使用 as!:

// 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.使用可选绑定(bind)检查orch是否为nil:

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

希望对您有所帮助。

关于swift - 无法使用类型为 '[String : String]?' 的索引下标类型为 'String' 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30020362/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com