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

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.

主站蜘蛛池模板: 柞水县| 北海市| 赤峰市| 卢氏县| 深圳市| 鹤山市| 集安市| 盐山县| 汉中市| 绥宁县| 阜宁县| 若尔盖县| 绥中县| 峨边| 达州市| 凤台县| 河东区| 宣恩县| 沽源县| 双峰县| 彩票| 抚州市| 玛沁县| 高尔夫| 大名县| 宜城市| 噶尔县| 万宁市| 玛纳斯县| 泰州市| 罗源县| 洪泽县| 武汉市| 古蔺县| 夏河县| 贵南县| 增城市| 兰考县| 平和县| 中超| 碌曲县|