我在下面重新创建了我的错误,当我试图在嵌套字典中设置属性时,我得到了错误
"Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value" on line 25, which is registrationInfo[whichType!]![propKey] = propVal .
我认为这来自于打开
registrationInfo[whichtype]!
它迫使我打开包装。基本上,我如何设置dict中还不存在的嵌套字典属性,因此,是的,为零,并且需要不是零,因为我需要设置它们?
import UIKit
class ViewController: UIViewController {
var registrationInfo = [String:[String:Any]]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func isTapped(_ sender: Any) {
appendToRegistrationInfo(registrationInfo: ®istrationInfo, whichType: "userInfo", propKey: "whichLanguage?", propVal: "swift")
}
func appendToRegistrationInfo(registrationInfo : inout[String : [String:Any]], whichType : String?, propKey : String, propVal : Any) {
if whichType != nil {
registrationInfo[whichType!]![propKey] = propVal
}
else {
for (type, _) in registrationInfo {
registrationInfo[type]![propKey] = propVal
}
}
}
}
您的实现在我看来不正确。您有一个类型为[String: [String: Any]]
的字典,我假设whichType
是外部字典的密钥,propKey
是内部字典的密钥。
键必须是非零的,这样才能索引到外部和内部字典中。然后,你可以做:
if var innerDict = registrationInfo[whichType] {
innerDict[propKey] = propVal
registrationInfo[whichType] = innerDict
} else {
registrationInfo[whichType] = [propKey: propVal]
}
if let type = whichType {
if let info = registrationInfo[info], let prop = registrationInfo[info][propKey]
{
registrationInfo[info][propKey] = propVal
}
}
当您通过键直接访问NSDictionary
值时,必须小心。
在启动if whichType != nil {
的块内尝试
对于else
块
for (type, _) in registrationInfo {
if let type = registrationInfo[type], let prop = registrationInfo[type]![propKey] {
registrationInfo[info][propKey] = propVal
}
}
它可以更好地实现,但我相信它可以保护您免受nil
错误的影响。