当前位置: 动力学知识库 > 问答 > 编程问答 >

ios - Swift shows nil value for Dictionary type

问题描述:

I have a dictionary of type < String, String>. It can access by index values like dictionary[0]. But i want to access each values in this in a simple way by using the key.

 var rows: [Dictionary<String, String>] = []

rows = [..] // assigned some value

var value = rows[0]["id"]

println(rows[0]) // ["id": "2", "name": "Bob", "age": "19"]

println(value) // I get nil value

How can i access by this key format. Any suggestions. Thanks in advance.

I tried to read values from a CSV file. And assigned to rows. It works fine when i print rows[0] it shows the correct value. But on the next line if i print rows[0]["id"] it gives me a nil value. And i tried with manual dictionary like

 rows = [["name": "alvin"]]

var value = rows[0]["name"]

println(value) // prints alvin

Whats the difference?

网友答案:

This could happen if your key has a space in it. Consider the following:

var rows: [Dictionary<String, String>] = []
rows = [["id ": "2", "name": "Bob", "age": "19"]] // assigned some value
var value = rows[0]["id"]
println(rows[0]) // ["id": "2", "name": "Bob", "age": "19"]
println(value) // I get nil value

To check your keys, print them out like this to see if there is any space in them:

for key in rows[0].keys {
    println("XXX\(key)XXX")
}

prints:

XXXid XXX
XXXageXXX
XXXnameXXX

showing that key id is followed by a space, but age and name are not.

分享给朋友:
您可能感兴趣的文章:
随机阅读: