user2985898
user2985898

Reputation: 1203

Swift two dimensional dictionary error

I create a two dimensional 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 it:

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 get the following compile error:

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

I will use an alternative solution for now but I don't understand the error and had no luck finding two dimensional dictionary examples. What is the correct way for a 2d dictionary?

Upvotes: 3

Views: 1822

Answers (2)

Duncan C
Duncan C

Reputation: 131408

Looking up a value in a dictionary returns an optional (since that key may not exist.) This epression:

locale[lang]["create"]

Should be

locale[lang]!["create"]

Instead.

Note that that code will crash if there is not an entry for the current language in your dictionary. 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
}

Upvotes: 3

Greg
Greg

Reputation: 25459

When you call locale[lang] it returns an optional so it should be changed to locale[lang]?["create"] or locale[lang]!["create"]

Upvotes: 0

Related Questions