Fast two dimensional dictionary error

I am creating a 2D dictionary like this and it compiles fine:

var locale : [String : [String : String]] =
    ["en" : ["create" : "Create", "cancel" : "Cancel"],
     "fr" : ["create" : "Creer", "cancel" : "Annuler"]]

      

But when using:

var lang = NSUserDefaults.standardUserDefaults().objectForKey("MyLanguage") as! String
let createButton = UIBarButtonItem(title: locale[lang]["create"],
            style: UIBarButtonItemStyle.Plain, target: self, action: "createAction:")
self.navigationItem.rightBarButtonItem = createButton

      

I am getting the following compilation error:

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

      

I'm going to use an alternative solution for now, but I don't understand the error and have no luck finding 2D dictionary examples. What's the correct way for a 2d dictionary?

+3


source to share


2 answers


Searching for a value in a dictionary returns optional (since this key may not exist.) This expression:

locale[lang]["create"]

      

Should be

locale[lang]!["create"]

      



Instead.

Note that this code will work if your dictionary does not have an entry for the current language. It would be safer to use optional binding:

if let createButtonTitle = locale[lang]?["create"]
{
  let createButton = UIBarButtonItem(
    title: createButtonTitle,
    style: UIBarButtonItemStyle.Plain, 
    target: self, 
    action: "createAction:")
  self.navigationItem.rightBarButtonItem = createButton
}

      

+3


source


When you call locale[lang]

it returns an optional parameter, so it should be changed to locale[lang]?["create"]

orlocale[lang]!["create"]



0


source







All Articles