Coding/Learn/swift/swift arrays and sets
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

LearnArrays, Sets & Higher-Order Collection Operations
7 / 20 0%
Lesson 07 of 20
9 mins read

Arrays, Sets & Higher-Order Collection Operations

PreviousNext Lesson
In Plain English

Master Swift primary sequence collections. Learn ordered, type-safe Arrays ([Element]), unordered unique-element Sets (Set<Element>), set algebra (union, intersection), and functional pipelines with map, filter, reduce, and sorted.

The Mental Model

"An Array is a sequential playlist where song order matters and songs can repeat. A Set is a collector bag of unique badges: adding a duplicate badge does nothing, and membership lookup is instant O(1)."

Deep Dive: How It Works

Array ([T]): Ordered collection with zero-indexed access (e.g. var fruits = ["Apple", "Banana"]).

Set (Set<T>): Unordered collection of unique values requiring elements to conform to the Hashable protocol.

Higher-Order Transformers: .map() transforms elements, .filter() keeps matching elements, .reduce() aggregates to single value.

Copy-on-Write: Collections are value types copied lazily on modification for maximum performance.

Syntax Blueprint

var list = [1, 2, 3]
list.append(4)
let evens = list.filter { $0 % 2 == 0 }
let unique = Set(list)

Declare arrays with [], filter with closure shorthand $0, and deduplicate with Set.

PointCore Rules to Remember

Point star
Type Safety: Arrays and Sets only accept elements matching their declared type (e.g. [Int] cannot store strings).
Point star
Set Algebra: Perform instant math operations: setA.intersection(setB), setA.union(setB), setA.subtracting(setB).
Point star
Shorthand Closures: Use $0, $1 for inline parameters inside map, filter, and reduce.

Common Beginner Traps & How to Fix Them

Mistake:Accessing an index >= array.count.

Why it happens: Swift array subscripting bounds-checks and traps with a fatal error on out-of-bounds.

How to fix: Check index < array.count or use array.indices.contains(index).

Pro Tip: Use array.first and array.last to safely retrieve optionals instead of subscripting when collections might be empty.

Live Interactive Example

Hit Run Code to see it live
Functional Array Pipeline: Filter, Map and Reduce
Swift 5.10 / LLVM
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Output Console
Click "Run Code" to view the rendered output.
How it works: Filtered to [20, 25, 30], doubled to [40, 50, 60], and reduced with + to sum 150.

Your Turn: Micro Challenge

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

Micro Exercise

Deduplicate and Sort Numbers

  • PointDeclare let rawNumbers = [5, 2, 8, 2, 5, 1, 9].
  • PointConvert to a Set to eliminate duplicates.
  • PointSort the set into ascending order using .sorted().
  • PointPrint "Sorted Unique: " followed by the sorted array.
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