hunterp
hunterp

Reputation: 15986

Cannot subscript a value of type '[String : String]?' with an index of type 'String'

   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"

Upvotes: 8

Views: 28536

Answers (1)

ABakerSmith
ABakerSmith

Reputation: 22969

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.

Upvotes: 22

Related Questions