Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

   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"

like image 415
hunterp Avatar asked May 03 '15 23:05

hunterp


1 Answers

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.

like image 103
ABakerSmith Avatar answered Sep 21 '22 04:09

ABakerSmith