iOS 12 Programming for Beginners
上QQ阅读APP看书,第一时间看更新

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.