Swift: Adding Elements

Adding Elements in Swift’s Dictionary:

Let’s discuss about adding elements to dictionary in Swift.

We could use the following subscript syntax to add a new key-value pair to a dictionary:

nameofDictionary[NewKey] = NewValue

It’s important to remember that when adding new dictionary elements, the new key and value must match the data types of the dictionary to which they’re being added, or an error will occur.

Let’s pretend we’ve made a dictionary of icecreamPrices:

var icecreamPrices = [
  "Vanilla": 4,
  "Coconut": 6
];

Using the following code, we can add a third element to icecreamPrices:

icecreamPrices["Mango"] = 8;

If we print() the value of icecreamPrices, we get something like this:

["Mango": 8, "Vanilla": 4, "Coconut": 6]

Helpful Tools:

Here are some useful tools to help you along your journey!

Setting up an IDE (Integrated Development Environment) can be difficult for beginners. The Online Compiler will enable you to run your code inside your browser without the need to install an IDE. If you need a more detailed explanation of a specific topic, the best place to find answers is in the Official Documentation.

Scroll to Top
%d bloggers like this: