Skip to content
Tutorials Center
My learning

Topics

Lesson 141 of 146 ยท Practice

Swift Cheat Sheet

A compact Swift 6 cheat sheet with runnable examples - variables, strings, optionals, collections, closures, types, protocols, errors, concurrency, access control and common conventions.

This page is a quick reference for the Swift you use every day. It is not a replacement for the lessons: each section links to the lesson that explains the idea in depth. Every code block that has a Run button is complete and runs in your browser against a real Swift 6 compiler, so you can change it and try your own variations. Tables and short snippets without a Run button are for lookup.

Use it the way you would use a map. When you forget how to write a switch with a where clause, or whether the label is at: or for:, find the section and copy from the example.

Variables, types and numbers

Use let for values that never change and var for values that do. Types are inferred, and Swift never converts between numeric types implicitly. See constants and variables, basic types and numbers.

Swift Cheat sheet: variables, numbers and strings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

formatted() is the modern way to format numbers and dates; String(format:) (Foundation) is the printf-style alternative. See string interpolation and formatting.

Type Notes
Int, Int8 ... Int64, UInt Int is 64 bits on 64-bit platforms; overflow traps unless you use &+, &-, &*
Double, Float Double is the default floating-point type
Bool only true or false; conditions must be Bool (no truthy values)
Character, String one grapheme cluster vs. a collection of them; indices are not integers
Substring a view into a String; convert with String(sub) before storing
Decimal exact base-10 numbers (Foundation), good for money

Control flow

if and switch can be expressions that produce a value. switch must be exhaustive and does not fall through. Ranges are first-class. See if and else, switch, loops and guard.

Swift Cheat sheet: control flow

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Optionals

An optional is a box that holds a value or nil. Unwrap it safely; force-unwrap (!) only when a nil would be a bug in your own program. See optionals and optionals in depth.

Swift Cheat sheet: optionals

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Operation Syntax
Declare var x: Int? (starts as nil)
Unwrap safely if let x { }, guard let x else { return }
Default x ?? 0
Chain a?.b?.c
Transform x.map { ... }, x.flatMap { ... }
Force unwrap x! traps if nil; avoid it for outside data
Silence failure try? f() gives nil on error

Collections and closures

Collections are value types with copy-on-write storage, so assigning one copies it lazily. Closures are written in braces, with $0, $1 shorthand; a closure that is the last argument goes after the parentheses. See arrays, dictionaries, sets and map, filter, reduce.

Swift Cheat sheet: arrays, sets, dictionaries and closures

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Need Use
Ordered, indexable Array
Unique, fast contains Set
Look up by key Dictionary
Pairs without a type tuple, (name: String, age: Int)
Lazy, one pass .lazy, sequence(first:next:)
Sort by several keys sorted { ($0.a, $0.b) < ($1.a, $1.b) }

Types: structs, classes, enums and protocols

Prefer structs (value semantics) and enums; use classes when you need identity, inheritance or shared mutable state. Protocols describe capabilities and can carry default implementations through extensions. See structs, classes, enumerations, protocols and generics.

Swift Cheat sheet: structs, classes, enums, protocols and generics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Notice the line deinit { print("counter released") }: the message appears when the last reference disappears at the end of the do block. That is ARC at work.

Access control

Keyword Visible from
private the enclosing declaration and its extensions in the same file
fileprivate the whole file
internal (default) the whole module
package all modules in the same package
public other modules can use it, but not subclass or override it
open other modules can subclass and override (classes only)

Common protocols to know

Protocol What it gives you
Equatable, Hashable ==, use as a dictionary key or in a Set (often synthesized)
Comparable <, sorted(), min(), max()
Codable JSON and other encodings in one line each way
Identifiable an id property, used by many frameworks
CustomStringConvertible the text print shows
Sequence, Collection for-in, map, filter and indexing for your own types
Error anything you can throw
Sendable safe to pass between tasks and actors

Errors and cleanup

Functions that can fail are marked throws; the caller must write try. You choose between handling the error (do/catch), converting it to an optional (try?) or crashing on purpose (try!, for impossible cases only). Typed throws (throws(MyError)) states exactly which error can come out. See error handling, typed throws and defer.

Swift Cheat sheet: errors, Result and defer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Form Meaning
try f() propagate the error to the caller
try? f() nil on error
try! f() trap on error: only for failures that mean a bug
fatalError("...") stop the program with a message
precondition(cond, "...") check in all builds
assert(cond) debug builds only; compiled out with -O

Concurrency

async functions can suspend; call them with await. Run things in parallel with async let or a task group; protect shared mutable state with an actor. Swift 6 checks for data races at compile time, so values crossing tasks must be Sendable. See async and await, task groups and actors.

Swift Cheat sheet: async let, task groups and actors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Five tasks tried to withdraw 30 from a balance of 100, and exactly three succeeded, no matter how the tasks were scheduled. That guarantee is what an actor provides: its methods run one at a time.

Tool Use it for
async let a fixed number of parallel calls
withTaskGroup a dynamic number of parallel jobs
Task { } start unstructured work from synchronous code
actor shared mutable state
Mutex (Synchronization) tiny critical sections without await
AsyncStream values over time
Task.checkCancellation() cooperative cancellation in long work

Naming and style conventions

  • Types and protocols are UpperCamelCase; everything else is lowerCamelCase. Acronyms keep one case: urlString, JSONDecoder.
  • Name things by their role at the call site: remove(at:), move(from:to:), contains(_:). Methods that read as a verb phrase mutate (sort()); noun-like or -ed/-ing forms return a new value (sorted()).
  • Boolean properties read as assertions: isEmpty, hasPrefix.
  • Prefer let, then structs, then small functions, then guard-based early exits.
  • Avoid force unwraps and as! except where a failure means a bug in your own code.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which line safely turns the text "42" into an Int with a fallback of 0?

    Int(_:) from a String returns an optional, and ?? supplies the default when parsing fails.
  2. 2. What is the difference between sort() and sorted()?

    Swift's naming guideline: the verb form mutates, the -ed form returns a new value.
  3. 3. Why must a switch over an enum list every case or have a default?

    Exhaustiveness is checked at compile time, so adding a case later shows you every switch that needs updating.
  4. 4. Which tool protects shared mutable state used by many tasks?

    An actor serializes access to its state, and Swift 6 rejects unprotected shared mutable globals.
  5. 5. What does defer do?

    Deferred blocks run on every way out of the scope, last-declared first, which makes them ideal for cleanup.

Summary

  • let first, var when needed; no implicit numeric conversions; use &+ and friends for deliberate wrap-around.
  • if and switch are expressions; switch is exhaustive and pattern-rich; prefer guard for early exits.
  • Unwrap optionals with if let, guard let, ?? and ?.; reserve ! for programmer errors.
  • Collections are value types; sort dictionary keys before printing; map, filter, reduce and compactMap cover most loops.
  • Prefer structs and enums, use classes for identity, and describe capabilities with protocols and generics.
  • Errors use throws, try, do-catch and Result; defer handles cleanup; typed throws names the error type.
  • Concurrency means async/await, task groups, actors and Sendable, all checked by the Swift 6 compiler.

Next: Common Swift Mistakes