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

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.

主站蜘蛛池模板: 蚌埠市| 收藏| 娱乐| 泸定县| 宜都市| 赣州市| 屏东市| 大庆市| 岑溪市| 民乐县| 扶余县| 丰都县| 称多县| 页游| 朝阳市| 吉水县| 余干县| 靖西县| 石景山区| 成武县| 惠东县| 丹棱县| 绥中县| 阳原县| 迁西县| 永靖县| 吉木萨尔县| 洮南市| 尉犁县| 麟游县| 墨竹工卡县| 姚安县| 焦作市| 女性| 灵宝市| 额济纳旗| 荔波县| 类乌齐县| 北流市| 巴彦淖尔市| 花莲市|