SWIFT dictionaries - Accessing a single value of a key with multiple values

时间:2015-06-26 10:30:44

标签: swift dictionary

To access the second value of the second key of the dictionary bellow:

This question is not about getting any value of a key, but an specific value if this value is an array.

For the following variable

var dict2 = ["key1" : "value1", "key2" : [ "value1" , "value2" ]]

This works (option 1)

let value2 = dict2["key2"]?[1] as? String
println(value2!)

But this do not (option2)

let value2 = dict2["key2"][1]

Other users suggested the second option, but that does not work. I am wandering why.

Why should I cast the type? I imagine if the value was an Int I would have to cast it as an Int. But that assumes I know what type of value is in there and it exists. So why calling it as an optional?

2 个答案:

答案 0 :(得分:4)

由于您的词典具有不同的值类型,因此它可能具有AnyObject作为值的类型。你会想把它投射到它的类型。此外,字典访问返回选项,因为键可能不存在于字典中,因此您需要打开该值才能访问它。最后,您的值是一个数组,因此使用数组索引(1来访问第二项,因为数组索引基于0)。这是一个具体的例子:

let dict = ["age" : 31, "names" : [ "Fred" , "Freddie" ]]

if let val = dict["names"]?[1] as? String {
    println(val)  // prints "Freddie"
}

由于数组索引超出范围会导致程序崩溃,为了完全安全,您需要执行以下操作:

if let array = dict["names"] as? [String] {
    if array.count > 1 {
        let name = array[1]
        println(name)
    }
}

此样式通过以下方式保护您:

  1. 如果密钥"names"不在您的字典中,if let将无法执行任何操作而不会崩溃。
  2. 如果您的值不是您认为的String数组,则if let将无效。
  3. 首先检查array.count,这可以确保您不会获得数组索引超出范围的错误。
  4. 要向"key2"添加值,您需要首先明确地为字典提供类型[String: AnyObject],因为Swift推断的类型是NSDictionary,并且该类型是不可变的,即使用var声明。

    var dict2:[String: AnyObject] = ["key1" : "value1", "key2" : [ "value1" , "value2" ]]
    
    if let value = dict2["key2"] as? [String] {
        dict2["key2"] = value + ["value3"]
    }
    

答案 1 :(得分:1)

如果您确定第二个键有两个元素,则可以使用以下方法访问第二个元素:

var value = dict[key2][1]