Link Menu Expand Document

Swift Programming

Dictionary Series · Lesson 1

Intro to Dictionaries

Understand dictionaries as key-value collections for fast lookup and structured data modeling.

Swift Programming Xcode iOS

What to focus on while watching

  • Dictionaries map unique keys to associated values.
  • They are ideal when lookup by identifier matters more than order.
  • Choose clear key types to keep data access predictable.

Lesson Notes and Walkthrough

A dictionary stores data in key-value pairs. Instead of finding data by index (like arrays), you find it by key. This is useful when each item has a unique identifier.

When to Use a Dictionary

  • When you need fast lookup by name, ID, or label.
  • When each value belongs to a unique key.
  • When order is less important than quick access.

Basic Swift Syntax

var scores: [String: Int] = ["Alex": 90, "Sam": 88]

This means keys are String values and stored values are Int.

Step-by-Step Example

var scores: [String: Int] = ["Alex": 90, "Sam": 88]
scores["Alex"] = 95                 // update value
let alexScore = scores["Alex"] ?? 0 // safe read

print(alexScore)
print(scores.count)

Why ?? Is Important

Looking up a key may return no value. The ?? operator gives a fallback so your app does not crash. Example: scores["Taylor"] ?? 0.

Common Beginner Mistakes

  1. Assuming every key always exists.
  2. Using inconsistent key names (for example "alex" vs "Alex").
  3. Using a dictionary when ordered data is required.

You may also like

Practice: Dictionary Basics

~7 min Beginner

Goal: Create a dictionary, update a key, and read values safely.

Steps

  1. Create a dictionary of student scores.
  2. Update one score by key.
  3. Print the updated value and key count.

Expected Output

Alex: 95
Total students: 2
Need a hint? Read values with optional handling: scores["Alex"] ?? 0.

Code

import Foundation

var scores: [String: Int] = ["Alex": 90, "Sam": 88]
scores["Alex"] = 95

print("Alex: \(scores["Alex"] ?? 0)")
print("Total students: \(scores.count)")