let orch = NSUserDefaults().dictionaryForKey("orch_array")?[orchId] as? [String:String]
orch[appleId]
Errors on the orch[appleId]
line with:
Cannot subscript a value of type '[String : String]?' with an index of type 'String'
WHY?
Question #2:
let orch = NSUserDefaults().dictionaryForKey("orch_array")?[orchId] as! [String:[String:String]]
orch[appleId] = ["type":"fuji"]
Errors with: "Cannot assign the result of this expression"
The error is because you're trying to use the subscript on an optional value. You're casting to [String: String]
but you're using the conditional form of the casting operator (as?
). From the documentation:
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.
Therefore orch
is of type [String: String]?
. To solve this you need to:
1. use as!
if you know for certain the type returned is [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. Use optional binding to check if orch
is nil
:
if let orch = NSUserDefaults().dictionaryForKey("orch_array")?[orchId] as? [String: String] {
orch[appleId] // No error
}
Hope that helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With