我目前正在学习 swift,我想知道为字典赋值和使用 updateValue 函数之间有什么区别。他们都更改或添加一个字典,其中包含您输入的名称以及您传递给该名称的值。
var states = [ "La" : "Las Vegas", "Ca" : "California", "We" : "Whatever" ]
//manually assigning/changing a value
states["La"] = "Ive changed"
println(states["La"])
//using the updateValue function
states.updateValue("Ive changed again", forKey: "La")
println(states["La"])
他们都给我相同的结果,问题是我的想法是否正确,我只想知道我应该使用第一个还是第二个选项以及何时使用。
最佳答案
只有一个区别,当您使用 updateValue
更新字典时,它会更新/插入值并返回存储在键中的先前值。 (如果该键不存在,则返回 nil)
你可以这样使用:
if let unwrappedPreviousValue = dictionary.updateValue("Midhun", forKey: "La")
{
println("Previous value: \(unwrappedPreviousValue)")
}
根据 Swift Standard Library Reference :
updateValue(_:forKey:)
Inserts or updates a value for a given key and returns the previous value for that key if one existed, or nil if a previous value did not exist.
Declaration
mutating func updateValue(value: Value, forKey key: Key) -> Value?
Discussion
Use this method to insert or update a value for a given key, as an alternative to subscripting. This method returns a value of type Value?—an optional with an underlying type of the dictionary’s Value
关于ios - 手动为字典赋值和使用 updateValue 函数有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29190855/