Swift Foundations
Core types, optionals, functions, collections, Unicode strings, value and reference semantics, errors, local source files and observable tests. No frameworks, concurrency, package manager or unsafe pointers.
Audience: Learners comfortable saving plain-text files and using a terminal.
Practice: 4 to 6 hours.
Runtime and boundaries: Use /usr/bin/swiftc -swift-version 6 -warnings-as-errors "Example.swift" -o "Practice", then ./Practice in a new practice folder. Replace Example.swift with the exact exported filename. The companion example instead compiles main.swift and "Study tools.swift" together. The harness uses an owned temporary module cache. Apple Swift 6.4 on this Mac is the only tested compiler; Swift 6 mode is not a complete conformance claim. No Foundation, SwiftUI, SwiftPM, downloads or external inputs are required. The browser exports text and does not run Swift.
Lessons
Compile before running
A Swift source file is checked and compiled to an executable. Compile success does not establish correct output. This pack records both, with Swift 6 mode and warnings treated as errors. Deliberately invalid fixtures are never run. Optimization, other targets and the Swift interpreter are not tested.
Types, constants and optionals
let fixes a binding; var allows reassignment. Swift does not implicitly convert Int to Double. An Int? can contain a value or nil; use optional binding or a documented fallback instead of forcing it. Int conversion accepts a syntax, not an application policy, so validate bounds separately.
Control flow and functions
if requires Bool. switch must cover all possibilities, often with default. Functions have parameter types, argument labels and a return type. A function can return nil for rejected input when that contract is clear. Keep arithmetic within a stated range.
Collections and order
Arrays have order; dictionaries and sets do not promise a report order. Sort keys or values before printing. Array access outside its indices traps, so use first or check indices for uncertain positions. The examples contain tiny authored collections, not arbitrary workloads.
Strings and Unicode
String.count counts extended grapheme clusters represented as Character values; utf8.count counts encoded bytes. Indexing uses String.Index rather than an integer offset. Canonically equivalent spellings can compare equal. A character is not necessarily one byte or Unicode scalar.
Value and reference semantics
Assigning a struct creates a separate value; assigning a class instance copies its reference. let on a class reference does not freeze its mutable properties. Arrays of class references still refer to the same objects. Swift uses automatic reference counting for classes; cycles and weak/unowned design are outside these examples.
Recoverable errors
A throwing function declares throws and callers use try. do/catch handles matching errors. A failed precondition or out-of-range array access is a trap, not a recoverable error for catch. These programs validate input and avoid deliberate traps; expected compiler failures are a separate test category.
Files, modules and test evidence
The companion is compiled into the same executable, not imported as a separately built module. With multiple files, top-level entry statements are in main.swift. The assertion exercise uses explicit checks with fatalError only on unexpected results; those failure branches are not deliberately executed. No arbitrary submitted code is sandboxed.
Reference cards
Binding: let / var
Constant binding or mutable variable.
Types: Int / Double / Bool
Explicit numeric conversion; conditions require Bool.
Absence: Int? / nil
Optional value or absence.
Unwrap: if let / guard let
Safely bind a present optional.
Fallback: value ?? fallback
Supply a value when optional is nil.
Flow: if / switch / for
Choose branches and visit sequences.
Functions: func f(_ x: Int) -> Int
Typed argument and return; underscore omits call label.
Ranges: 0...120 / 0..<3
Closed versus half-open ranges.
Arrays: [Int] / first / indices
Ordered collection with checked access.
Mappings: [String: Int] / keys.sorted()
Optional lookup and explicit output order.
Strings: count / utf8.count
Grapheme clusters versus UTF-8 bytes.
Values: struct
Copied value; reference-valued properties can still alias.
References: final class / ===
Identity of class instances.
Errors: Error / throws / try / catch
Model and handle recoverable failures.
Transforms: filter / map / reduce
Create selections, transformations and accumulated values.
Build: swiftc -swift-version 6
Compile in pinned language mode before executing.
Supporting configuration: Run instructions.txt
Use /usr/bin/swiftc -swift-version 6 -warnings-as-errors "Example.swift" -o "Practice", then ./Practice in a new practice folder. Replace Example.swift with the exact exported filename. The companion example instead compiles main.swift and "Study tools.swift" together. The harness uses an owned temporary module cache. Apple Swift 6.4 on this Mac is the only tested compiler; Swift 6 mode is not a complete conformance claim. No Foundation, SwiftUI, SwiftPM, downloads or external inputs are required. The browser exports text and does not run Swift.
Examples and practice
Code below is reading material, not an execution console. Download the edition for the complete example files and companion modules.
Swift 01 - Typed values
Explicit conversion chooses floating-point division. The small positive input stays within Int range.
let name = "Ada"
let minutes: Int = 25
let half = Double(minutes) / 2
print("\(name): \(minutes) minutes")
print("Integer half: \(minutes / 2)")
print("Decimal half: \(half)")
Expected:
Ada: 25 minutes Integer half: 12 Decimal half: 12.5
Intentionally invalid Swift: expected compiler diagnostic containing cannot convert value of type 'String'. Expected rejection; not a successful program. No runtime execution follows rejection.
let minutes: Int = "25"
Swift 02 - Optional conversion
Conversion and the application range are separate checks. This accepts Swift Int syntax, including a leading plus; it does not claim a digits-only policy.
func minutes(_ text: String) -> Int? {
guard let value = Int(text), (0...120).contains(value) else {
return nil
}
return value
}
for text in ["25", "no", "121"] {
if let value = minutes(text) {
print("\(text): \(value)")
} else { print("\(text): rejected") }
}
Expected:
25: 25 no: rejected 121: rejected
Intentionally invalid Swift: expected compiler diagnostic containing must be unwrapped. Expected rejection; not a successful program. No runtime execution follows rejection.
let value: Int? = nil let required: Int = value
Swift 03 - Branches and loops
The default covers every remaining Int, including negative values. This classifier does not validate input.
func band(_ value: Int) -> String {
switch value {
case 0: return "none"
case 1...30: return "short"
default: return "outside short range"
}
}
for value in [0, 20, 45] { print("\(value): \(band(value))") }
Expected:
0: none 20: short 45: outside short range
Swift 04 - Function contracts
Argument labels explain call sites. Bounded operands avoid overflow, and nil denotes rejected input.
func scaled(minutes: Int, factor: Int = 2) -> Int? {
guard (0...120).contains(minutes), (1...3).contains(factor) else {
return nil
}
return minutes * factor
}
print(scaled(minutes: 20) ?? -1)
print(scaled(minutes: 20, factor: 3) ?? -1)
print(scaled(minutes: -1) == nil)
Expected:
40 60 true
Swift 05 - Deterministic collections
Filtering keeps array order. Dictionary output is explicitly sorted; the lookup fallback is safe here because the keys came from this unchanged dictionary.
let sessions = [10, 30, 20]
let selected = sessions.filter { $0 >= 20 }
print(selected.map { String($0) }.joined(separator: ", "))
print("Total: \(sessions.reduce(0, +))")
let totals = ["reading": 20, "coding": 40]
for key in totals.keys.sorted() {
print("\(key): \(totals[key] ?? 0)")
}
print("Unique: \(Set(sessions + [10]).count)")
Expected:
30, 20 Total: 60 coding: 40 reading: 20 Unique: 3
Swift 06 - Text is not bytes
The combining accent joins the preceding letter as one Character. Canonical equivalence does not mean identical UTF-8 bytes.
let text = "Cafe\u{301}"
print("Characters: \(text.count)")
print("UTF-8 bytes: \(text.utf8.count)")
print("Equivalent: \(text == "Caf\u{e9}")")
if let first = text.first { print("First: \(first)") }
Expected:
Characters: 4 UTF-8 bytes: 6 Equivalent: true First: C
Swift 07 - Values and references
The struct is copied as a value. Both class bindings refer to the same instance; let prevents rebinding but permits this mutable property.
struct ValueLog { var minutes: Int }
final class SharedLog {
var minutes: Int
init(_ minutes: Int) { self.minutes = minutes }
}
let original = ValueLog(minutes: 10)
var copy = original
copy.minutes = 20
let shared = SharedLog(10)
let alias = shared
alias.minutes = 30
print("Values: \(original.minutes), \(copy.minutes)")
print("References: \(shared.minutes), \(alias.minutes)")
print("Same object: \(shared === alias)")
Expected:
Values: 10, 20 References: 30, 30 Same object: true
Intentionally invalid Swift: expected compiler diagnostic containing cannot assign to value. Expected rejection; not a successful program. No runtime execution follows rejection.
let minutes = 10 minutes = 20
Swift 08 - Recoverable errors
Only the explicit error is recoverable here. The final catch handles other errors allowed by the untyped throws contract instead of allowing them to propagate out of this entry point. No runtime trap is deliberately triggered.
enum StudyError: Error { case outsideRange }
func checkedDouble(_ value: Int) throws -> Int {
guard (0...120).contains(value) else { throw StudyError.outsideRange }
return value * 2
}
for value in [20, -1] {
do { print(try checkedDouble(value)) }
catch StudyError.outsideRange { print("rejected") }
catch { print("unexpected error") }
}
Expected:
40 rejected
Intentionally invalid Swift: expected compiler diagnostic containing call can throw. Expected rejection; not a successful program. No runtime execution follows rejection.
enum E: Error { case problem }
func fail() throws { throw E.problem }
fail()
Swift 09 - Compile local sources
Save both files together and compile main.swift plus "Study tools.swift" with the same flags. This is one executable built from two source files, not a separately imported library. studyTotal assumes its intermediate sums fit in Int; only the bounded authored values are demonstrated.
print("Companion: \(studyTotal([10, 20, 30]))")
Expected:
Companion: 60
Companion file: Study tools.swift
func studyTotal(_ values: [Int]) -> Int {
return values.reduce(0, +)
}
Swift exercise A - Optional mean
An optional expresses that an empty or out-of-contract collection has no accepted mean. The input-size and value bounds also keep the sum small.
func mean(_ values: [Int]) -> Double? {
guard !values.isEmpty, values.count <= 10,
values.allSatisfy({ (0...120).contains($0) }) else { return nil }
return Double(values.reduce(0, +)) / Double(values.count)
}
print(mean([10, 20, 30]) ?? -1)
print(mean([]) == nil)
Expected:
20.0 true
Practice: Compute a mean for up to ten minutes values in 0...120. Return nil for empty, oversized or invalid input.
Swift exercise B - Value copy
Array and this struct have value semantics. Replacing Session with a class changes the aliasing behavior.
struct Session { var title: String; var minutes: Int }
let original = [Session(title: "Read", minutes: 10)]
var edited = original
if !edited.isEmpty { edited[0].minutes = 20 }
print("Original: \(original.first?.minutes ?? 0)")
print("Edited: \(edited.first?.minutes ?? 0)")
Expected:
Original: 10 Edited: 20
Practice: Copy a one-row array of value records, edit the copied row and show that the original is unchanged.
Swift exercise C - Observable tests
All four checks execute at runtime. An unexpected result would terminate with a failure; the successful evidence does not claim that failure branch was executed.
func doubleMinutes(_ value: Int) -> Int? {
guard (0...120).contains(value) else { return nil }
return value * 2
}
let cases: [(Int, Int?)] = [(0, 0), (20, 40), (120, 240), (-1, nil)]
var passed = 0
for (input, expected) in cases {
guard doubleMinutes(input) == expected else { fatalError("wrong result") }
passed += 1
}
print("Assertions: \(passed) passed")
Expected:
Assertions: 4 passed
Practice: Test zero, normal input, upper bound and rejected negative input with observable failure on a mismatch.
Prompt templates
These are editable planning prompts in the downloadable workbench; they do not contact an AI service here.
Build a bounded example
For {language}, help with {goal}. Runtime: {runtime}. Constraints: {constraints}. Provide complete source, exact commands, expected output and supported tool versions. Do not claim checks ran without evidence.Debug a reproducible failure
For {language}, help with {goal}. Runtime: {runtime}. Constraints: {constraints}. Separate parser or compiler diagnostics, process failures and wrong results; reduce the reproduction. Do not claim checks ran without evidence.Test observable behavior
For {language}, help with {goal}. Runtime: {runtime}. Constraints: {constraints}. Cover empty, boundary and failure cases; distinguish proposed tests from executed tests. Do not claim checks ran without evidence.Refactor with evidence
For {language}, help with {goal}. Runtime: {runtime}. Constraints: {constraints}. Preserve outputs and behavior; explain regression checks and tool-specific assumptions. Do not claim checks ran without evidence.Document the contract
For {language}, help with {goal}. Runtime: {runtime}. Constraints: {constraints}. State input types, side effects, error policy, portability limits and actual test evidence. Do not claim checks ran without evidence.Explain with practice
For {language}, help with {goal}. Runtime: {runtime}. Constraints: {constraints}. Use an original example, predicted output, an exercise and a separate solution. Do not claim checks ran without evidence.Further reading
- Swift book: The Basics — Types, constants and optionals.
- Swift book: Collection Types — Array, set and dictionary semantics.
- Swift book: Structures and Classes — Value versus reference semantics.
- Swift book: Functions — Parameters, labels, return values and bounds-oriented function design.
- Swift book: Strings and Characters — Character, Unicode representation and string indexing.
- Swift book: Error Handling — Throws, try and recoverable errors.
- Swift book: Control Flow — Branches, switch exhaustiveness and loops.
- Swift book: Automatic Reference Counting — Class instance lifetime and reference ownership; cycles are outside the exercised examples.
Download the offline edition
Complete Atlas 0.11.0 ZIP (6,079,970 bytes) · 411-page guide and catalogue PDF · Versioned source JSON
Unzip the edition and open Programming and Scripting Atlas.html, Web Foundations.html, Python Foundations.html, SQL Foundations.html, Shell Foundations.html, TypeScript Foundations.html Data Formats Foundations.html, C Foundations.html C++ Foundations.html, Ruby Foundations.html, Perl Foundations.html, Swift Foundations.html, Makefile Foundations.html, awk Foundations.html, sed Foundations.html, jq Foundations.html, XSLT 1.0 Foundations.html, Tcl Foundations.html, Expect Foundations.html or Objective-C Foundations.html locally. The original interactive workbenches retain their offline prompt-building, local presets and export controls. Read the included README before running examples yourself. The workbench does not execute pasted code or call an AI service; prompt text is for you to inspect and use separately.
Version 0.11.0 is pinned here. The other 257 registry entries remain planned; this edition does not claim complete language coverage.
Evidence and limits
Objective-C adds 12 accepted native programs, four separate compiler or warning-policy rejections, 120 root checks and 147 independent native checks. Two rejection fixtures are warnings promoted by -Werror; they are not intrinsic syntax failures. No rejected fixture was executed. Tests dated 26 October 2026 used Apple Clang 21.0.0, ARC, C17 base mode, macOS SDK 27.0 headers and system Foundation 6.9 (5027.0.69) on macOS 27.0.1 arm64. This is introductory macOS/Foundation coverage, not iOS, GNUstep, Objective-C++, UI, concurrency or cross-platform coverage. No sanitizers, leak detector, race analysis, allocation/disk-full/permission fault injection or asynchronous timing tests were run. Trusted authored fixtures and process bounds do not establish an arbitrary-code sandbox.
The pinned Atlas 0.11.0 evidence records 607 browser checks, 55 Python harness checks plus four unittest methods, 74 SQL checks, 515 shell checks across 71 runs, 99 TypeScript checks, 51 Data Formats checks, 119 C checks, 116 C++ checks, 97 Ruby checks, 97 Perl checks, 105 Swift harness checks and 97 Makefile harness checks, 145 awk checks, 145 sed checks, 161 jq checks, 157 XSLT checks, 150 Tcl checks and 161 Expect checks. These are separate measures. Tcl and Expect tests are dated 26 October 2026 on installed Tcl 8.5.9 / Expect 5.45 with Tcl 8.5.9 on macOS arm64. These old versions are recorded teaching evidence, not deployment recommendations. Tcl has 12 accepted programs and Expect has 12 accepted controllers; each has four expected evaluation failures, not static compilation passes. Tcl has nine scenarios, five expected nonzero; Expect has seven scenarios, four expected nonzero. Expect default controllers invoke 15 toy children, including two expected child failures; one scenario also expects a failed child. Controller success does not mean every child succeeds. The authoring release records 100 owned-runner regression checks and 109 independent runner checks separately. Only authored fixtures and retained native child handles are covered. Cooperative cleanup requires event-loop progress; outer-timeout child cleanup remains uncertain without complete wait receipts. The retired PID-inspection branch was not retried. No sign-ins, secrets, network or external application control are taught or tested by this pack. awk and sed are text-processing languages; their examples use fixed authored ASCII input and the C locale with installed awk 20200816 and macOS sed on one platform. jq and XSLT each have 12 accepted examples and four separately rejected programs. jq has 21 scenarios, including five contract errors and one no-result status; XSLT has 20 scenarios, including five terminating messages and one CLI parameter rejection. Expected nonzero outcomes are not successful programs. Tests dated 26 October 2026 used jq 1.7.1-apple and XSLT 1.0 with libxslt 1.1.35/libxml2 2.9.13, fixed trusted programs and tiny authored inputs in the C locale on macOS arm64. These old installed XML libraries are recorded learning environments, not recommendations for untrusted-document processing. No imports, external documents, DTDs, custom/external entities, extension functions or generated source are covered. Command flags and bounds are not a complete sandbox. Standalone XPath remains planned; supporting XPath 1.0 expressions are limited to these XSLT examples. These tests do not establish GNU-tool equivalence, Unicode behavior, arbitrary-script safety or cross-platform portability. Swift has 12 accepted programs and four expected static rejections; Makefile has 12 accepted default targets, four expected parser rejections, eight additional scenarios and one expected recipe failure. Makefile is build scripting, not a general-purpose language. The Swift and Makefile test execution dates remain 25 October 2026. awk and sed tests are dated 26 October 2026. Delivery verification does not replace or refresh test execution dates. TypeScript includes 12 accepted programs executed as JavaScript and nine intentionally invalid cases correctly rejected. Each C/C++ pack has 12 accepted programs run normally and with AddressSanitizer/UndefinedBehaviorSanitizer, plus four expected compiler rejections that are never executed. Ruby and Perl each have 12 syntax-accepted programs executed and four expected syntax rejections; rejected cases are not successful programs. Syntax checks may execute compile-time code and are not arbitrary-code sandboxes. Sanitizer results cover executed paths only; leak detection and allocation-failure injection were not tested and memory safety is not proved.
Tested environments are Chrome 155, CPython 3.9.6, SQLite CLI 3.54.0, macOS sh/Bash 3.2.57/Zsh 5.9, TypeScript 6.0.3, Node 24.18.0 Apple Clang 21.0.0, Ruby 2.6.10p210 and Perl 5.34.1, Apple Swift 6.4 in Swift 6 mode and GNU Make 3.81 on one arm64 macOS host. C uses a C17 subset; C++ uses a C++20 subset with libc++ 220106. Python 3.9.6 is unsupported upstream. Ruby 2.6 is end-of-life upstream; the recorded installed interpreter is not a recommended modern runtime. Data Formats uses installed Tomli 1.0.3 through a private fallback; the Python tomllib branch was not run. No new-installation recommendation, complete language/format conformance, schema certification, hardened untrusted XML parsing or general-purpose execution sandbox is established. Other platforms, browsers and screen readers remain unverified. The 145 official references belong to the saved Atlas review, not fresh website-time verification.