Skip to content
Learn Netverks

Lesson

Step 14/36 39% through track

dictionaries-swift

Dictionaries

Last reviewed May 28, 2026 Content v20260528
Track mode
server_compiled
Means
Compiled runner
Reading
~1 min
Level
beginner

This lesson

This lesson teaches Dictionaries: the syntax, patterns, and safety habits you need before advancing in Swift.

Teams still ship Dictionaries in Swift codebases—skipping it leaves gaps in debugging and code reviews.

You will apply Dictionaries in contexts like: iPhone/iPad/Mac apps, server-side Swift (niche), and Apple toolchain projects.

Write Swift in main.swift with print(), click Run on server—the dev runner swiftc compiles and runs the binary (requires Swift toolchain, typically macOS; LEARNING_RUNNER_ENABLED=true).

When you can explain the previous lesson's ideas without copying starter code.

Dictionary maps keys to values with hash-based lookup—like Map in Java, dict in Python, or objects in JavaScript (with different semantics).

Syntax and access

var scores: [String: Int] = ["Ada": 98, "Lin": 87]
scores["Grace"] = 92

if let ada = scores["Ada"] {
    print(ada)
}

Subscript returns optional value—missing keys yield nil, not a crash.

Iteration

for (name, score) in scores.sorted(by: { $0.key < $1.key }) {
    print("\(name): \(score)")
}

Important interview questions and answers

  1. Q: Dictionary key requirements?
    A: Keys must conform to Hashable—strings, integers, enums often qualify.
  2. Q: Missing key behavior?
    A: Subscript returns Value?—use nil-coalescing or guard let when key must exist.

Self-check

  1. What type is returned by dict["missing"]?
  2. How do you add or update a key-value pair?

Pitfall: Subscript returns optional—missing keys yield nil, not a crash.

Interview prep

Missing key?

Subscript returns Value?—nil when absent.

Key requirements?

Keys must conform to Hashable.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Playground

Runs on the configured server runner (dev: npm run runner with LEARNING_RUNNER_ENABLED=true). Output appears below the editor.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • Dictionary keys hashable?
  • Default value subscript?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump