ios - 手动为字典赋值和使用 updateValue 函数有什么区别?

标签 ios swift dictionary

我目前正在学习 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/

相关文章:

iphone - 为什么被调用者返回自动释放的对象而不是返回保留的对象并让调用者释放对象?

ios - 如何使用 NSUserDefaults 在 Swift 中存储自定义类数组?

swift - 在 Swift 4 中处理 Firebase 5 身份验证错误

python - 将值附加到字典

java - 如何以良好的方式存储配置/属性数据?

ios - 快速添加基于键的分组字典元素的值

iphone - 在 cocos2d 层顶部的 uitableview 中制作自定义 uitableviewcell

ios - 一起使用 CGContextFillPath 和 CGContextStrokePath? iOS

ios - ipad mini 和 ipad air 有什么区别?

ios - UIImage 数组没有出现在 ios 模拟器中