Swift: Dictionaries

Dictionaries in Swift:

Let’s begin with Dictionaries in Swift.


A dictionary is a collection of paired data, often known as key-value pairs, that is arranged in an unordered manner.

var myDictionary = [
  "Key 1": "Value 1",
  "Key 2": "Value 2",
  "Key 3": "Value 3",
  "Key 4": "Value 4"  


In a dictionary, each key is unique.

Hence keys can use to access, remove, add, or change the value associated with them.

// Each key is unique even if they all contain the same value
var groceryStore = [
  "Bread": 20,
  "Tissue": 20,
  "Milk": 20

Type Consistency:

The data types of the keys and values in a dictionary must be consistent.

// Contains only String keys and Int values
var ageOfEmployees = [
  "Alex": 31,
  "Lisa": 22,
  "Max": 21

Initialize a Populated Dictionary:

Because dictionary literals are lists of key-value pairs separated by commas. So, it can use to populate dictionaries with data.

var zipCodes = [
  "Alaska": 99501,
  "Arizona": 85001,
  "California": 90001,

  "Arkansas": 71601 

Initialize an Empty Dictionary:

A dictionary with no key-value pairs refers to as an empty dictionary.

Therefore, there are several ways for initializing an empty dictionary; so the method chosen is purely a matter of personal preference and has no impact on the dictionary.

// Initializer syntax:
var yearlyFemalePopulation = [Int: Int]()
// Empty dictionary literal syntax:
var yearlyMalePopulation: [Int: Int] = [:]

Adding to a Dictionary:

Subscript syntax can use to add a new key-value pair to a dictionary by adding a new key enclosed in brackets [] after the dictionary’s name and a new value after the assignment operator (=).

var pronunciation = [
  "Dictionary": "dik·shuh·nuh·ree",
  "code": "kowd"
// New key: "water", New value: "waa·tr"
pronunciation["water"] = "waa·tr"

Removing Key-Value Pairs:

Set the value of a key to nil with subscript syntax or use the .removeValue() method to remove a key-value pair from a dictionary.

Hence to remove all the values from a dictionary, append the function .removeAll() to it.

var myLibrary = [
  "To Kill a Mockingbird": "Harper Lee",
  "It Ends With Us": "Colleen Hoover",
  "Verity": "Colleen Hoover"
// Remove value by setting key to nil
myLibrary["It Ends With Us"] = nil
// Remove value using .removeValue()
myLibrary.removeValue(forKey: "To Kill a Mockingbird")
// Remove all values

Modifying Key-Value Pairs:

Use the .updateValue() method or subscript syntax to alter the value of a key-value pair by appending brackets [] to a dictionary’s name and then adding an assignment operator (=) followed by the modified value.

var studentID = [
  "Carry": 1226,
  "Jake": 1227,
  "Drake": 1248,
  "Nancy": 1249
// Change value using subscript syntax
studentID["Carry"] = 1246
// Change value using .updateValue()
studentID.updateValue(1247, forKey: "Jake")

.isEmpty Property:

The .isEmpty property returns true if a dictionary contains no key-value pairs and false if the dictionary contains key-value pairs. For example:

var grocery = [String:Int]() 
// Check if dictionary is empty
print(grocery.isEmpty)  // Prints true
grocery["Cereals"] = 3  
// Check if dictionary is empty
print(grocery.isEmpty)  // Prints false

.count Property:

The .count property returns an integer indicating the number of key-value pairs in a dictionary.

var bakeryItems = [
  "Eggs": 12,
  "Cupcakes": 10,
  "Breads": 2,

  "Cookies": 20
print(bakeryItems.count)  // Prints: 4

Assigning a Value to a Variable:

Set the value of a variable to dictionaryName[keyValue] to assign the value of a key-value pair to it.

When you assign the value of a key-value pair to a variable, an optional value is returned. Hence optional unwrapping can use to extract the value. For example:

var fruitCost = [
  "Apple": "5$",
  "Banana": "4$",
  "Apricot": "10$",
print("The price of apple is \(fruitCost["Apple"])")
// Prints: The price of apple is Optional("5$")
if let bananaCost = fruitCost["Banana"] {
  print("The price of banana is \(bananaCost)")
// Prints: The price of banana is 4$

Iterating Over a Dictionary:

To loop through the keys and values of a dictionary, use a forin loop. For example:

var scores = [
  "Alice": 92,
  "Carry": 61,
  "Hayden": 79,
  "Lisa": 77
// Iterate through both keys and values
for (Names, scores) in scores {
  print("\(Names) has \(scores) scores.")
// Iterate only through keys
for Names in scores.keys {
// Iterate only through values
for scores in scores.values {

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: