Start free trial
Trending New Genres Authors
EnglishEnglish
EspañolSpanish
简体中文Chinese
繁體中文Chinese (Traditional)
FrançaisFrench
DeutschGerman
日本語Japanese
PortuguêsPortuguese
ItalianoItalian
한국어Korean
РусскийRussian
NederlandsDutch
العربيةArabic
PolskiPolish
हिन्दीHindi
Tiếng ViệtVietnamese
SvenskaSwedish
ΕλληνικάGreek
TürkçeTurkish
ไทยThai
ČeštinaCzech
RomânăRomanian
MagyarHungarian
УкраїнськаUkrainian
IndonesiaIndonesian
DanskDanish
SuomiFinnish
БългарскиBulgarian
עבריתHebrew
NorskNorwegian
HrvatskiCroatian
CatalàCatalan
SlovenčinaSlovak
LietuviųLithuanian
SlovenščinaSlovenian
СрпскиSerbian
EestiEstonian
LatviešuLatvian
فارسیPersian
മലയാളംMalayalam
தமிழ்Tamil
اردوUrdu
Searching...
SoBrief
The Swift Programming Language

The Swift Programming Language

Write Swift with confidence: understand the choices behind safer code and Apple's app ecosystem.
by Apple Inc. 2014 500 pages
4.15
479 ratings
Listen
Immersive
V2.3
Amazon Kindle Audible
Try Full Access for 3 Days
Unlock listening & more!
Continue

Key Takeaways

Let Swift's type system catch mistakes before your users do

Safety is built in. Swift was designed for iOS and OS X development, aiming to combine performance with a readable style and fewer common programming errors. Its compiler checks types before a program runs, while type inference fills in many declarations from context. A number does not silently become a string, and an integer cannot stand in for a Boolean condition. When conversion is needed, the code must say so explicitly.

Feedback comes quickly. A small program can begin at the file's top level without a main function, and Xcode playgrounds show results as code changes. Swift also connects to Cocoa and Objective-C, giving developers a route to use existing Apple frameworks. The guide's examples use Swift as it existed in 2014, so their exact syntax is historical.

Analysis

What's striking is that the compiler acts as an early reviewer: it forces assumptions about data to become visible before those assumptions reach users. This resembles a checked contract in mathematics, where a proof obligation narrows the set of possible mistakes. That benefit is not unlimited. Types can establish that a value is an integer, but cannot by themselves establish that the integer is a valid age, account balance, or array index. Strong type checking works best when developers also model meaningful domain rules.

Make absence explicit, and unwrap values only after checking

Missing is a real state. An optional is a type that can hold either a value of its underlying type or no value, represented by nil. Unlike a special sentinel number, an optional can describe absence for integers, strings, and custom types alike. A string-to-number conversion may fail, so its result is optional rather than an integer that pretends success is guaranteed.

Check before using. Optional binding tests for a value and makes the unwrapped result available inside a conditional block. Optional chaining carries out a property or method access only when each optional link exists, returning nil if a link is absent. Forced unwrapping with an exclamation mark is a promise that a value exists; breaking that promise causes a runtime error. A default can instead be supplied with the nil-coalescing operator.

Analysis

Optionals make uncertainty part of the interface instead of leaving it as an undocumented convention. This is valuable wherever data arrives from outside the program, such as user input, files, or network responses. The distinction also resembles the difference between a missing database field and a field containing an ordinary value: collapsing the two can produce misleading logic. The tradeoff is extra branching. That friction is useful when absence matters, but can become noise if a design marks values optional without identifying a plausible reason they might be absent.

Choose structs for independent values, classes for shared identity

Copies and references differ. Structures and enumerations are value types: assigning one to another gives the new variable an independent value. In the guide's example, changing a copied display resolution from 1920 pixels wide to 2048 leaves the original unchanged. Classes are reference types: two variables can point to the same instance, so a change made through one is visible through the other. The identity operator distinguishes two references to the same object from two objects that merely compare as equal.

Choose by behavior. A small geometric size or coordinate is a natural value because copies can stand alone. A shared object with identity, inheritance, or a managed lifecycle may fit a class. Swift strings and collections also have value semantics, while the implementation can delay physical copying until necessary.

Analysis

The distinction is less about whether a type is large or small than about whether shared change is part of its meaning. Value semantics make local reasoning easier because a function receiving a value cannot quietly alter another holder's copy. Reference semantics are useful when several parts of a system must observe one evolving entity. A design can still misuse either choice: copying a value does not make its contents logically immutable, and shared references can make behavior hard to trace. The best choice is the one that makes ownership and change unsurprising.

Use enums and exhaustive switches to make impossible states harder

States have a defined shape. Swift enumerations are full types, not merely names for integers. A card suit can be one of four declared cases, while a server response can be either a result carrying sunrise and sunset times or an error carrying a message. Associated values let each case carry the information it needs without forcing every case into the same data shape.

Handle every case. A switch must account for all possible values, either through explicit cases or a default. It can match more than single constants: patterns can inspect ranges, tuples, and associated values, and a where clause can add a condition. Unlike C-style switches, cases stop after a match unless fallthrough is explicitly requested. This reduces accidental execution of unrelated branches.

Analysis

An enumeration with associated values functions like a compact, typed vocabulary for a system's states. That can prevent invalid combinations, such as an error response that also carries success-only data. Exhaustive switching adds a useful maintenance signal: when a new case is introduced, affected code can be identified rather than silently overlooking it. The design still depends on choosing good cases. A catch-all default can hide new situations, so explicit cases are often more informative when every state deserves deliberate handling.

Treat functions as values to reuse behavior without duplication

Behavior can travel. A Swift function has a type determined by its inputs and output. It can be stored in a variable, passed to another function, or returned from one. A closure is a callable block of code that can also capture values from the surrounding scope. The guide uses closures to customize sorting and to map integers into digit-name strings, while shorter syntax lets the compiler infer types from context.

Generics reduce repetition. A generic stack can push and pop values of any one chosen type, rather than requiring separate stacks for integers and strings. Constraints narrow the permitted types when an operation needs a capability, such as equality comparison. The result is reusable code that stays type-checked instead of falling back to unstructured, universal data.

Analysis

Functions as values separate a general process from the policy that fills in its details. A sorting routine can manage ordering mechanics while its caller supplies the comparison rule. This is a form of dependency inversion: the reusable operation depends on a promised behavior, not on one hard-coded choice. Generics apply the same idea to data. Abstraction has a cost, though. A very short closure can conceal intent, and elaborate constraints can become harder to read than a few straightforward specialized functions.

Program to capabilities with protocols, then extend types locally

Protocols describe promises. A protocol lists the properties, methods, or initializers a type must provide, without dictating its implementation. A dice game can require a dice property and a play method; any conforming game can then be used where that protocol is expected. Code typed to the protocol can rely on its declared capabilities, not on extra features of one particular class.

Extensions add behavior. An extension can add methods or computed properties to an existing type, or declare that type's conformance to a protocol. The guide extends built-in types and uses a delegate protocol to let a Snakes and Ladders game report when it starts, advances turns, and ends. The game can notify different delegates without knowing their concrete types.

Analysis

Protocols make interchangeable behavior explicit, which supports testing and reduces dependence on a particular class hierarchy. Extensions offer a practical way to organize related capabilities near their use, including for types whose original implementation is unavailable. Together, they favor composition over forcing every relationship into inheritance. There is a boundary to watch: a protocol should express a coherent capability, not become a grab bag of unrelated requirements. Also, an extension can add behavior but cannot override existing functionality, so it is not a universal patch mechanism.

Initialize every object completely, and audit who keeps it alive

Construction has checkpoints. Swift requires stored properties to receive valid initial values before an instance is ready. Class initialization proceeds in two phases: each class initializes its own properties and delegates up to its superclass, then the hierarchy can further customize the instance. Designated initializers are the main construction route; convenience initializers provide shortcuts that ultimately delegate to one. A failable initializer can return no instance when inputs are invalid.

References govern lifetime. Automatic Reference Counting, or ARC, releases a class instance when no strong references remain. Two objects that strongly refer to each other can keep each other alive indefinitely. In the guide's person and apartment example, making the tenant link weak breaks the cycle because an apartment may have no tenant. An unowned link fits a relationship that must remain valid for its lifetime, but using it after its target disappears causes a runtime error.

Analysis

Initialization rules and reference counting address two different forms of correctness: whether an instance begins in a valid state, and whether it remains alive only as long as needed. The distinction resembles resource ownership in systems design, where construction establishes invariants and cleanup releases scarce resources. ARC removes routine manual bookkeeping, but does not remove the need to understand object graphs. Weak and unowned references encode different lifecycle assumptions, not interchangeable performance preferences. A mistaken unowned assumption can turn an otherwise manageable lifetime problem into a crash.

Use typed collections and Unicode-aware strings for reliable data

Collections declare their contents. An array stores ordered values of one type; a dictionary maps unique keys to values, but has no guaranteed iteration order. Looking up a missing dictionary key returns an optional, because the requested entry may not exist. Swift also treats these collections as value types, while using implementation optimizations to avoid unnecessary physical copies.

Text has layers. A Swift Character represents an extended grapheme cluster, which can contain one or more Unicode scalar values. The letter é, for example, can be represented as one scalar or as an e plus a combining accent, yet count as one displayed character in either form. UTF-8 bytes, UTF-16 code units, Unicode scalars, and human-perceived characters are different ways to view text. Counting characters can require traversing the string.

Analysis

Typed collections prevent a common class of errors by making the allowed contents clear at the point of use. Unicode-aware character handling solves a subtler problem: what a person sees as one character need not be one storage unit. This distinction matters in text limits, cursor movement, and user-visible counting. The guide's key lesson is not that one representation is always best, but that representation must match the operation. Byte length may suit storage or transmission, while a user-facing character count needs grapheme-aware behavior.

Prefer explicit control flow and checked arithmetic over silent surprises

Branches state their conditions. Swift requires Boolean expressions in if statements, so an integer cannot accidentally be treated as true or false. Its switch statement checks cases without implicit fallthrough, and ranges distinguish whether the final endpoint is included. A half-open range is useful for zero-based array indexes because it stops before the collection's count.

Boundaries should be visible. Ordinary integer arithmetic traps on overflow rather than quietly wrapping; overflow operators are available when wraparound is intended. Assertions can verify conditions that must hold, such as an index being inside a matrix's dimensions, and help reveal violations during development. They are debugging checks, not a replacement for handling invalid external input safely.

Analysis

These rules make control flow more legible by removing ambiguity that older C-family conventions sometimes tolerate. Explicit Boolean tests and exhaustive switches function as small local proofs: readers can see what the code considers valid. Checked arithmetic similarly turns an out-of-range result into a visible failure instead of corrupted state. Assertions are especially useful for internal assumptions, but they should not be mistaken for user-facing error handling. A robust interface must still decide what to do when real-world input violates expectations.

Expose only the API other modules need, and keep the rest private

Access defines the boundary. Swift provides public, internal, and private access. Public declarations are available to importing modules, internal declarations stay within the module, and private declarations are limited to their source file. Most declarations default to internal. A public type does not automatically make all its members public, so a framework author must deliberately expose each part of its API.

Visibility must be consistent. A public function cannot sensibly expose a parameter or return type that is private, since users of the function could not access that type. Setter access can also be narrower than getter access, allowing other code to inspect a value without changing it. The guide presents access control as a way to separate a framework's supported interface from implementation details.

Analysis

Access control is an architectural tool, not merely a way to hide code. A smaller public surface reduces the number of promises a library must preserve and gives internal implementation room to change. Restricting setters can also protect invariants while still making state observable. The nuance is that privacy can obstruct legitimate reuse if boundaries are drawn too narrowly. Good module design therefore asks two questions: what must a client be able to do, and what should remain an implementation choice? The language supplies controls, but judgment supplies the boundary.

Analysis

This 2014 guide is both an introduction and a technical reference. Its tutorial begins with a tiny program, then builds outward through values, control flow, functions, object models, protocols, memory, and finally the formal grammar. That structure matters: Swift is presented not as a collection of clever syntax, but as a coordinated set of constraints intended to make application code more expressive without giving up compiler-enforced discipline or access to Apple's existing frameworks.

The most consequential design choice is making uncertainty and identity visible. Optionals say that a value may be absent. Enums define the states a value may occupy. Value types distinguish independent copies from shared class instances. Protocols describe required behavior without demanding one inheritance tree. Each choice narrows accidental ambiguity, while generics preserve reuse without discarding type information. The language's safety story is therefore cumulative: no feature eliminates bugs, but several features make assumptions inspectable and errors easier to locate.

The tradeoff is a learning curve. Initializer delegation, optional handling, reference cycles, access rules, and generic constraints all require the programmer to state decisions that looser languages may leave implicit. That explicitness can feel ceremonial in small programs. Its value rises as code crosses module boundaries, handles external data, or shares mutable objects. The guide's playground emphasis supplies a counterweight: experimentation gives beginners immediate evidence while the type system supplies guardrails.

The source is historically specific. It documents Swift as published in 2014, including syntax and library interfaces that have since changed. Its durable value is conceptual rather than as a current API manual. Readers should retain the models of optionals, value and reference semantics, protocols, generics, Unicode, and ARC, while checking contemporary documentation before using particular spellings or APIs. Seen this way, the book is a record of a language's design ambitions and a usable introduction to the reasoning behind them.

Summary in 30 Seconds
Swift uses compiler-checked types and explicit conversions to catch mismatches before a program runs. Optionals represent missing values, while enums and exhaustive switches make possible states and their handling explicit. Value types create independent copies; classes share identity, so reference cycles can keep objects alive unless weak links break them. Protocols and generics enable reusable, type-checked code. This 2014 guide's concepts endure, but its syntax and APIs may have changed.
Contains spoilers

Last updated:

Report Issue

Review Summary

4.15 out of 5
Average of 479 ratings from Goodreads and Amazon.

The Swift Programming Language receives mostly positive reviews, with readers praising its clarity and comprehensive coverage of Swift. Many find it well-written and easy to follow, especially for those with prior programming experience. Some readers appreciate the book's structure, starting with a concise introduction followed by in-depth explanations. However, a few criticize its organization and pacing, suggesting it could be divided into separate beginner and advanced texts. Overall, it's considered a valuable resource for learning Swift, particularly for iOS and Mac development.

Your rating:
4.57
129 ratings
Want to read the full book?

Glossary

Optional

Value that may be absent

An Optional represents either a value of a specified type or the absence of a value, written nil. The type annotation marks this possibility explicitly, so code must check for presence before safely using the underlying value. Optionals can represent absence for basic values and custom types, not only object references.

Optional Binding

Check and extract a value

Optional binding checks whether an optional contains a value and, if so, makes that value available as a temporary constant or variable inside a conditional or loop. It combines the presence check with extraction, avoiding a separate forced unwrap and keeping the unwrapped value within a scope where its existence is established.

Value Type

Independent copied value

A value type is copied when assigned or passed to a function, so the recipient behaves as an independent value rather than another reference to shared identity. In Swift, structures and enumerations are value types. Strings, arrays, and dictionaries also have value semantics, though implementation optimizations can avoid copying storage when no independent change is needed.

Reference Type

Shared object identity

A reference type is accessed through references to an instance rather than by copying the instance whenever it is assigned or passed. Swift classes are reference types. Multiple variables can refer to the same class instance, so mutations through one reference are observable through the others. Class instances can also participate in inheritance and ARC.

Closure

Callable code that captures context

A closure is a self-contained block of callable code that can be passed around, stored, or returned from a function. It may capture constants and variables from the scope where it is created, allowing those values to remain available when the closure runs elsewhere. Global functions, nested functions, and inline closure expressions are related forms.

Protocol

Requirements for a capability

A protocol specifies requirements for properties, methods, initializers, or subscripts without providing their implementation. A class, structure, or enumeration can conform by supplying the required members. Code that uses a protocol can depend on the declared capability rather than the particular concrete type that provides it.

Generics

Reusable code with type guarantees

Generics let functions and types operate on placeholder types that are determined when the code is used. Constraints can require those types to inherit from a class or conform to protocols, ensuring needed operations are available. Generic arrays, dictionaries, stacks, and functions can therefore be reusable without treating their contents as untyped values.

Automatic Reference Counting (ARC)

Automatic class lifetime management

ARC tracks strong references to class instances and deallocates an instance when no strong references remain. It handles routine memory management automatically, but strong reference cycles can keep instances alive indefinitely. Weak and unowned references express relationships that should not keep their targets alive.

Strong Reference Cycle

References that keep each other alive

A strong reference cycle occurs when two class instances, or a class instance and a closure, hold strong references to each other. Each reference keeps the other object alive, preventing ARC from reaching zero strong references and reclaiming memory. Weak or unowned references can break the cycle when they correctly match the relationship's lifetime.

Extended Grapheme Cluster

One human-readable character unit

An extended grapheme cluster is one or more Unicode scalar values that together represent a single human-readable character. For example, an accented letter may be encoded as one scalar or as a base letter plus a combining mark. Swift's Character type represents these clusters, so character counts can differ from byte or code-unit counts.

Two-Phase Initialization

Initialize, then customize

Two-phase initialization is Swift's class construction process. First, each class initializes the stored properties it introduces and delegates to its superclass until the full instance has valid initial values. Then the class hierarchy can further customize the instance. Compiler checks prevent properties or methods from being used before the instance is fully initialized.

About the Author

Apple Inc. is the author of "The Swift Programming Language," which serves as the official guide to the Swift programming language. As a technology company known for its innovative products and software ecosystems, Apple developed Swift as a modern, safe, and fast programming language for iOS, macOS, watchOS, and tvOS applications. The company's decision to create and maintain this comprehensive language guide demonstrates their commitment to supporting developers within their ecosystem. By providing this resource, Apple aims to facilitate the adoption and mastery of Swift among programmers interested in creating applications for Apple platforms.

Download PDF

To save this The Swift Programming Language summary for later, download the free PDF. You can print it out, or read offline at your convenience.
Download PDF
File size: 0.32 MB     Pages: 17

Download EPUB

To read this The Swift Programming Language summary on your e-reader device or app, download the free EPUB. The .epub digital book format is ideal for reading ebooks on phones, tablets, and e-readers.
Download EPUB
File size: 1.38 MB     Pages: 20
Want to read the full book?
Follow
Listen
Home
Swipe
Library
Get App
Try Full Access for 3 Days
Listen, bookmark, and more
Compare Features Free Pro
📖 Read Summaries
Read unlimited summaries. Free users get 3 per month
🎧 Listen to Summaries
Listen to unlimited summaries in 40 languages
—
❤️ Unlimited Bookmarks
Free users are limited to 4
—
📜 Unlimited History
Free users are limited to 4
—
📥 Unlimited Downloads
Free users are limited to 1
—
Risk-Free Timeline
Today: Get Instant Access
Listen to full summaries of 26,000+ books. That's 12,000+ hours of audio!
Day 2: Trial Reminder
We'll send you a notification that your trial is ending soon.
Day 3: Your subscription begins
You'll be charged on Nov 24,
cancel anytime before.
Consume 2.8× More Books
2.8× more books Listening Reading
Our users love us
1M+ readers
Trustpilot Rating
TrustPilot
4.6 Excellent
This site is a total game-changer. I've been flying through book summaries like never before. Highly, highly recommend.
— Dave G
Worth my money and time, and really well made. I've never seen this quality of summaries on other websites. Very helpful!
— Em
Highly recommended!! Fantastic service. Perfect for those that want a little more than a teaser but not all the intricate details of a full audio book.
— Greg M
Save 62%
Yearly
$119.88 $44.99/year/yr
$3.75/mo
Monthly
$9.99/mo
Start a 3-Day Free Trial
3 days free, then $44.99/year. Cancel anytime.
Unlock a world of fiction & nonfiction books
26,000+ books for the price of 2 books
Read any book in 10 minutes
Discover new books like Tinder
Request any book if it's not summarized
Read more books than anyone you know
#1 app for book lovers
Lifelike & immersive summaries
30-day money-back guarantee
Download summaries in EPUBs or PDFs
Cancel anytime in a few clicks

Why one summary?

Scanner
Find a barcode to scan

⭐
⭐
⭐
We have a special gift for you
Open
38% off
DISCOUNT FOR YOU
⭐
⭐
⭐
$79.99
$49.99/year
Only $4.16 per month
Continue
2 taps to start, super easy to cancel
Settings
General
Widget
Loading...