Coding/Learn/swift/swift dictionaries and tuples
Swift Foundational Course
01.Introduction, Safety Philosophy & The Toolchain
02.Constants (let), Variables (var) & Type Inference
03.Strings, String Interpolation & Multiline Literals
04.Operators, Range Types & Nil-Coalescing
05.Control Flow: If, Switch Pattern Matching & Guard Statements
06.Optionals, Optional Binding & Optional Chaining
07.Arrays, Sets & Higher-Order Collection Operations
08.Dictionaries, Default Lookups & Tuples
09.Loops, Defer Execution & Labeled Statements
10.Functions, Argument Labels & In-Out Parameters
11.Closures, Trailing Closures & Shorthand Arguments
12.Enums, Raw Values & Associated Values (Tagged Unions)
13.Error Handling: Throwing Functions, Do-Catch & Try Options
14.Structures (struct), Value Semantics & Mutating Methods
15.Classes, Reference Semantics & Inheritance
16.Automatic Reference Counting (ARC), Weak & Unowned References
17.Properties: Stored, Computed, Observers (didSet) & Lazy
18.Protocols, Protocol Extensions & POP (Protocol-Oriented Programming)
19.Generics, Type Constraints & Associated Types
20.Capstone: Production Async/Await Cache & JSON API Engine
Course Certificate0%

Complete all lessons to earn

LearnDictionaries, Default Lookups & Tuples
8 / 20 0%
Lesson 08 of 20
9 mins read

Dictionaries, Default Lookups & Tuples

PreviousNext Lesson
In Plain English

Work with associative key-value mappings and ad-hoc compound types. Master Swift Dictionaries ([Key: Value]), subscript lookups with default values, and Tuples ((httpCode: 200, status: "OK")) for lightweight multi-value returns.

The Mental Model

"A Dictionary is like an airport flight information board: look up flight "AA100" (key) and instantly see the destination "JFK" (value). A Tuple is like a passport: a small bound booklet holding your name, birth year, and nationality together."

Deep Dive: How It Works

Dictionaries: Hash map storing unique Hashable keys mapped to values ([String: Int]).

Dictionary Subscripts: Subscripting dict[key] returns an Optional Value (Value?) because keys may not exist.

Default Parameter Lookups: dict[key, default: 0] returns a non-optional default value if key is missing.

Tuples: Group multiple values into a single compound type ((Int, String) or named (code: 200, message: "OK")).

Syntax Blueprint

var counts: [String: Int] = ["swift": 100]
let count = counts["go", default: 0]
let response = (code: 200, status: "OK")

Use [Key: Value] for hash tables with default values, and (name: value) for tuples.

PointCore Rules to Remember

Point star
Optional Subscripts: Subscripting a dictionary without default returns an Optional (dict["key"] -> String?).
Point star
Tuples as Function Returns: Ideal for returning multiple named values from a function without declaring a full struct.
Point star
Tuple Destructuring: let (code, msg) = response unpacks values into distinct local constants.

Common Beginner Traps & How to Fix Them

Mistake:Using tuples for complex persistent data models.

Why it happens: Tuples lack methods, property observers, and protocol conformance.

How to fix: Use structs for complex entities and reserve tuples for temporary grouped values.

Pro Tip: You can remove a key from a dictionary by assigning nil to its subscript: dict["tempKey"] = nil.

Live Interactive Example

Hit Run Code to see it live
Dictionary Frequency Tally and Tuple Return
Swift 5.10 / LLVM
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Output Console
Click "Run Code" to view the rendered output.
How it works: Named tuple accessed via .status and .latencyMs, and dictionary tallied frequencies with default: 0.

Your Turn: Micro Challenge

No pressure! Edit the starter code below and test your solution with instant feedback.

Micro Exercise

Query Product Price with Default Fallback

  • PointDeclare let catalog: [String: Double] = ["laptop": 999.0, "mouse": 25.0].
  • PointQuery the price of "monitor" using default: 0.0.
  • PointPrint "Price of monitor: $\(price)".
1
2
3
4
5
6
Sandbox Output
Click "Run & Check" to test your solution.

Finished reading and practicing?

Mark this lesson as completed to update your course progress.

PreviousNext Lesson
Overview100 SheetLearnCertificates