SWIFT

Swift Dictionary: Syntax, Usage, and Examples

A Swift dictionary is a collection type that stores key-value pairs, letting you associate specific identifiers (keys) with corresponding data (values). Each key in a dictionary Swift structure must be unique, making it ideal for fast lookups and efficient data retrieval.

How to Use a Swift Dictionary

The syntax for creating a dictionary in Swift is simple and flexible. You define a dictionary using square brackets, with the key and value types separated by a colon.

var studentGrades: [String: Int] = ["Alice": 90, "Bob": 85, "Clara": 92]

In this example, studentGrades maps student names (String) to their grades (Int). You can also use type inference when assigning a literal value:

swift
CopyEdit
var capitals = ["France": "Paris", "Japan": "Tokyo", "India": "New Delhi"]

To create an empty dictionary, specify the key and value types:

var inventory: [String: Int] = [:]

Accessing and Modifying Values

You access a value using its key:

let grade = studentGrades["Alice"]  // Output: Optional(90)

Because the key might not exist, the result is an optional.

To update or add a new value:

studentGrades["Bob"] = 88  // Updates Bob's grade
studentGrades["Diana"] = 91  // Adds a new student

To remove a value:

studentGrades["Alice"] = nil  // Deletes Alice’s entry

When to Use a Dictionary Swift

Dictionaries are extremely useful when you need to associate values with unique identifiers or retrieve values efficiently using keys. Here are some common use cases:

1. Storing Configuration or Settings

You can use a dictionary in Swift to store app settings or preferences:

let settings = ["theme": "dark", "fontSize": "medium"]

2. Mapping IDs to Records

In apps that deal with user IDs, session tokens, or other unique identifiers, a Swift dictionary lets you map these to associated data.

let users = [101: "Emma", 102: "Noah", 103: "Liam"]

3. Grouping Values by Key

With Swift dictionary grouping, you can cluster values under a common key—like grouping names by the first letter.

let names = ["Alice", "Aaron", "Bob", "Becky"]
let grouped = Dictionary(grouping: names, by: { $0.prefix(1) })
// Result: ["A": ["Alice", "Aaron"], "B": ["Bob", "Becky"]]

4. Counting Frequencies

Dictionaries are excellent for counting how often something occurs—like word frequency in a string or visits on a page.

let words = ["apple", "banana", "apple"]
var countDict: [String: Int] = [:]

for word in words {
    countDict[word, default: 0] += 1
}

Examples of Swift Dictionary

Example 1: Creating and Accessing Values

var countryCodes = ["US": "United States", "FR": "France", "JP": "Japan"]
print(countryCodes["FR"] ?? "Unknown")  // Output: France

Example 2: Iterating Over a Dictionary

let prices = ["apple": 1.2, "banana": 0.8, "cherry": 2.0]

for (fruit, price) in prices {
    print("\(fruit): $\(price)")
}

This prints each fruit and its price in a readable format.

Example 3: Checking for Existence

if let value = countryCodes["JP"] {
    print("Found: \(value)")
} else {
    print("Key not found.")
}

Swift dictionaries return optional values, so checking with if let is common.

Example 4: Using Default Values

You can supply a fallback value using the default: parameter:

let population = ["NY": 8_336_817]
let bostonPop = population["Boston", default: 0]  // Output: 0

Learn More About Swift Dictionaries

Swift Ordered Dictionary

Dictionaries in Swift are unordered by default, which means the order of items isn't guaranteed. However, since Swift 5.2, the order in which you insert elements tends to be preserved in practice—but it's not something you should rely on for logic.

If maintaining order matters, consider using OrderedDictionary from the Swift Collections package.

import OrderedCollections

var orderedDict: OrderedDictionary = ["first": 1, "second": 2]
orderedDict["third"] = 3

This keeps keys in insertion order and allows indexed access:

print(orderedDict[0])  // Output: 1 (value of "first")

Dictionary in Swift vs Array

A dictionary Swift type offers constant-time access for keys, whereas arrays require iteration to find a match. Choose dictionaries for fast lookup and arrays for ordered sequences.

  • Use a dictionary when:
    • You need to find a value by a unique key.
    • You need to count or group data.
    • You want to avoid duplicates in the key space.
  • Use an array when:
    • You care about order.
    • You want to store duplicate values.
    • You need to loop through everything in sequence.

Filtering and Mapping Dictionaries

You can filter or transform dictionaries using high-order functions:

let scores = ["Amy": 95, "Ben": 82, "Chris": 99]
let highScorers = scores.filter { $0.value > 90 }
// Result: ["Amy": 95, "Chris": 99]

To transform values:

let bonusScores = scores.mapValues { $0 + 5 }

You can also transform keys and values together:

let doubledScores = Dictionary(uniqueKeysWithValues: scores.map { ($0.key, $0.value * 2) })

Merging Dictionaries

You can merge two dictionaries using the merge(_:uniquingKeysWith:) method.

var config = ["theme": "light", "volume": "low"]
let override = ["theme": "dark"]

config.merge(override) { (_, new) in new }
// Result: ["theme": "dark", "volume": "low"]

Nested Dictionaries

A dictionary can contain other dictionaries. This is useful when you want to structure complex data like API responses or nested categories.

let library = [
    "fiction": ["1984": "Orwell", "Dune": "Herbert"],
    "nonfiction": ["Sapiens": "Harari"]
]

if let author = library["fiction"]?["Dune"] {
    print("Author of Dune: \(author)")
}

Dictionary Capacity and Performance

Dictionaries in Swift are highly optimized. Still, if you expect to insert a large number of entries, you can reserve capacity in advance:

var cache = [String: Int]()
cache.reserveCapacity(1000)

This improves performance by reducing reallocations.

Converting Dictionary to Array

Swift lets you convert dictionaries into arrays easily. This is handy when you want to sort or map the entries.

let sortedKeys = prices.keys.sorted()
let valuesArray = prices.values.map { $0 }

You can also sort by value:

let sortedByPrice = prices.sorted { $0.value < $1.value 

Summary

A Swift dictionary gives you fast, structured access to related data through unique keys. From mapping user IDs to names, counting items, grouping elements, or storing configurations, dictionaries offer incredible flexibility and performance. You can create, update, remove, and loop through a dictionary in Swift with just a few lines of code.

More advanced features—like Swift dictionary grouping or using an ordered dictionary Swift package—expand the possibilities for structured, predictable data handling.

Learn to Code in Swift for Free
Start learning now
button icon
To advance beyond this tutorial and learn Swift by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2025 Mimo GmbH

Reach your coding goals faster