Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Error Accessing Data From Dictionary with Array of Dictionaries

Tags:

ios

swift

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.

like image 231
Travis M. Avatar asked Feb 26 '15 18:02

Travis M.


People also ask

What is the difference between dictionary and array in Swift?

Arrays are used to hold elements of a single type. We can have an array of strings, characters, integers etc. In Swift, we can easily create one array using array literal i.e. put the elements of the array inside a square bracket. Again, dictionary in Swift is a collection that holds key-value pairs.

What is a dictionary key in Swift?

Swift 4 dictionaries use unique identifier known as a key to store a value which later can be referenced and looked up through the same key. Unlike items in an array, items in a dictionary do not have a specified order. You can use a dictionary when you need to look up values based on their identifiers. A dictionary key...

How to filter values from a dictionary in Swift?

Swift 4 allows you to filter values from a dictionary. var closeCities = cityDistanceDict.filter { $0.value < 1000 } If we run the above code our closeCities Dictionary will be. Swift 4 allows you to create grouping of Dictionary values. var cities = ["Delhi","Bangalore","Hyderabad","Dehradun","Bihar"]

How do you iterate through a dictionary in Swift?

We use the for loop to iterate over the elements of a dictionary. For example, We can use the count property to find the number of elements present in a dictionary. For example, In Swift, we can also create an empty dictionary. For example, In the above example, we have created an empty dictionary.


2 Answers

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]
}
like image 111
kellanburket Avatar answered Nov 10 '22 01:11

kellanburket


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

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

let dict = array![0] 
like image 21
Gwendle Avatar answered Nov 10 '22 01:11

Gwendle