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.
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.
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...
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"]
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.
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]
}
It doesn't like calling a subscript on an optional.
If you're sure data["Blah"] exists, you should do:
let dict = array![0]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With