I have an array with data for my TableView sections
let menuItems : Dictionary<String,Dictionary<String,String>>[] = [
[
"data" : [
"name":"test",
"image":"test.png"
]
],
[
"data" : [
"name":"test2",
"image":"test2.png"
]
]
]
I'm trying to access it by using subscript
func tableView(tableView: UITableView!, titleForHeaderInSection section: Int) -> String! {
return menuItems[section]["data"]["name"]
}
and have the error
Could not find member 'subscript'
I have read a lot of similar questions on stackoverflow, but still haven't understood how to fix it. I tried to unwrap with "!" symbol and used another variables - no result.
Could you explain how does it works, please?
println(menuItems[0]["data"]!["name"])
Short answer: menuItems[0]["data"] returns an optional dictionary.
You can look at the below REPL output to understand the issue.
Dictionary<String, String>!.In real code, you would probably want to check for optionals, and handle nils accordingly.
1> let menu: Dictionary<String, Dictionary<String, String>>[] = [["dict1" : ["key" : "val"]], ["dict2" : ["key" : "val"]]]
menu: Dictionary<String, Dictionary<String, String>>[] = size=2 {
[0] = {
[0] = {
key = "dict1"
value = {
[0] = {
key = "key"
value = "val"
}
}
}
}
[1] = {
[0] = {
key = "dict2"
value = {
[0] = {
key = "key"
value = "val"
}
}
}
}
}
2> menu[0]
$R1: Dictionary<String, Dictionary<String, String>> = {
[0] = {
key = "dict1"
value = {
[0] = {
key = "key"
value = "val"
}
}
}
}
3> menu[0]["key"]
$R2: Dictionary<String, String>? = nil
4> menu[0]["dict1"]
$R3: Dictionary<String, String>? = Some {
[0] = {
key = "key"
value = "val"
}
}
5> menu[0]["dict1"]["key"]
REPL:6:1: error: could not find member 'subscript'
menu[0]["dict1"]["key"]
^~~~~~~~~~~~~~~~~~~~~~~
6> menu[0]["dict1"]!
$R4: Dictionary<String, String> = {
[0] = {
key = "key"
value = "val"
}
}
7> menu[0]["dict1"]!["key"]
$R5: String? = "val"
8> menu[0]["dict1"]!["key"]!
$R6: String = "val"
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