Swift - Error accessing data from a dictionary with an array of dictionaries

I have a very simple example of what I would like to do

private var data = [String: [[String: String]]]() override func viewDidLoad() { super.viewDidLoad() let dict = ["Key": "Value"] data["Blah"] = [dict, dict] } @IBAction func buttonTap(sender: AnyObject) { let array = data["Blah"] let dict = array[0] //<---- error here println(dict["Key"]) } 

Basically, I have a dictionary whose values ​​contain an array of dictionaries [String: String]. I enter data into it, but when I go to access the data, I get this error:

Cannot tune value of type '[[[String: String])]?' with an index of type 'Int'

Please let me know what I am doing wrong.

+6
source share
2 answers

Your array constant is optional. A dictionary subheading always returns optional. You have to deploy it.

 let dict = array![0] 

Even better,

 if let a = array { let dict = a[0] } 
+12
source

I do not like to call the index on the optional.

If you are sure that [Blah] data exists, you should do:

 let dict = array![0] 
+3
source

Source: https://habr.com/ru/post/983061/


All Articles