6
votes

I have a very simple example of what I'd 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 [String: String] dictionaries. I stuff data into it but when I go to access the data, I get this error:

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

Please let me know what I'm doing wrong.

2
data["Blah"] returns an optional and must be unwrapped. – This must have been answered before ...Martin R
Yes, sorry, that was obvious once I look at it. I thought it was an issue with swift handling nested objects so my searches turned up empty. Thank you!Travis M.
I tried to close as a duplicate but if you do a search for this particular error message, there doesn't appear to be any references. I'll just leave it as is in case it can help someone who overlooked the obvious "?" like I did.Travis M.

2 Answers

12
votes

Your constant array is an optional. Subscripting a dictionary always returns an optional. You have to unwrap it.

let dict = array![0]

Better yet,

if let a = array {
   let dict = a[0]
}
3
votes

It doesn't like calling a subscript on an optional.

If you're sure data["Blah"] exists, you should do:

let dict = array![0]