8
   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"

1

1 Answer 1

22

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.

Sign up to request clarification or add additional context in comments.

4 Comments

@abakersmith Thank you, and now, if I get slightly more complex, why can't I [orchId] as! [String: [String:String] and then it won't let me orch["id"] = ["type":"fuji"]
Could you post that as an edit to your question? It's a bit hard to following without proper formatting.
That error is because you've declared orch as a constant (with let). If you use var instead you'll be able to edit its contents.
Is there any benefit to doing it the first way? Seems like the second way does exactly the same thing except shorter and safer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.