官术网_书友最值得收藏!

Adding and updating dictionary elements

Let's add another item to our dictPizzas dictionary:

dictPizzas["meat"] = 17.99

Once you add this line of code, your code snippet should look like this:

This is the shorthand method for adding an item to a dictionary. After the dictionary variable, we add the key inside the brackets. Since the key for this dictionary is strings, we must put this key in quotes. Next, we assign a double to our value. Now, our dictionary has two items. This syntax is also used to update a dictionary item. Let's change the price of meat pizza to 16.99:

dictPizzas["meat"] = 16.99 

Have a look at the code. It should look like this:

Instead of using the shorthand syntax, you can use the updateValue(_:forKey:) method. This method does almost the same thing as the shorthand syntax. If the value does not exist, it creates the item; if it does exist, it will update the item. The only difference is that, when using the updateValue(_:forKey:) variable, it actually returns the old value after performing the update. Using this method, you will get an optional value because it's possible that no value exists in the dictionary. Now, let's change the value from 16.99 to 15.99:

if let oldValue = dictPizzas.updateValue(15.99, forKey: "meat") { 
  print("old value \(oldValue)") 
}

Your code should now look like this:

Since we do not need the old value, we will just use the shorthand syntax to add a couple more pizzas:

dictPizzas["specialty"] = 18.99 
dictPizzas["chicken"] = 16.99

Your code and output should now look like this:

Now that we have some data inside our dictionary, let's see how we can access that data.

主站蜘蛛池模板: 津市市| 镇雄县| 虎林市| 松潘县| 庆元县| 东乡县| 肇源县| 黔西县| 连江县| 义马市| 沁源县| 昌乐县| 磐安县| 克拉玛依市| 叶城县| 阿拉善左旗| 南城县| 新蔡县| 克东县| 青阳县| 怀柔区| 青海省| 鸡西市| 镇宁| 曲靖市| 蚌埠市| 黑水县| 三明市| 东阿县| 三都| 淅川县| 洞口县| 综艺| 潍坊市| 合作市| 永康市| 新兴县| 萝北县| 特克斯县| 峨眉山市| 临江市|