Skip to main content
Quick Reference

Swift Cheatsheet

Swift on one page — values, optionals, collections, structs and classes, errors, memory, async, and the traps around force unwrap and string indexes.

10 sections 10 tables 14 code snippets

Run a file

The compiler

swift hello.swift

A constant and a variable

let title = "Dune"
var pages = 412
pages += 1
print(title)

The names

NameMeaning
letA constant. Assigning again is a compile error
varA variable. The type stays the one inferred from the first value
Inference412 is an Int. Write : Double when that guess is wrong
printWrites a line. A semicolon is optional
nilOnly an optional can hold it
swiftRuns a file. Xcode is the Apple IDE. SwiftUI is a separate framework

This page is the Swift language. The samples run as a file or in a playground.

Optionals

Bind it before you use it

let published: Int? = nil
if let year = published {
  print(year)
}

A stand-in

let shown = published ?? 2026
print(shown)

Optional rules

FormResult
Int?Either an Int or nil
if letThe inner name is a real Int. The outer one stays optional
guard letLeaves the function when the value is nil. The name lives on after the guard
??Uses the right-hand value when the left one is nil
!Force unwrap. A nil stops the program
title?.countOptional chaining. The whole expression is optional

Collections

An array

var books = ["Dune", "Neuromancer"]
books.append("Foundation")
print(books[0])

A dictionary

let prices = ["Dune": 18.5]
let price = prices["Dune"] ?? 0
print(price)

Collection rules

TypeDetail
[String]An array. books[0] traps when the index is missing
[String: Double]A dictionary. The subscript is optional, because the key may be absent
SetUnique values. Order is not part of the value
Empty literalvar names: [String] = []. A bare [] has no type to infer
Value copyAssigning an array copies the value. Changing the copy leaves the original
0..<books.countA half-open range. 1...3 includes 3

Functions

A named argument

func total(price: Double, count: Int = 1) -> Double {
  return price * Double(count)
}
print(total(price: 18.5, count: 2))

Call rules

PieceEffect
price:The argument label at the call. The name inside the function can differ
count: Int = 1A default. Callers may omit it
-> DoubleThe return type. Omit it when the function returns nothing
_ as the labelThe caller passes the value with no label
Closurebooks.map { $0.count } uses $0 for the first argument
inoutThe function can write back to the caller variable. Pass it with &

Structs and classes

A struct copies

struct Book {
  var title: String
  var pages: Int
}
var book = Book(title: "Dune", pages: 412)
book.pages = 500

Which one to pick

KindBehavior
structA value. Assignment copies it. The memberwise init is written for you
classA reference. Assignment shares the object. You write init
mutatingRequired on a struct method that changes self
==Value equality, when the type conforms to Equatable
===Identity. True when two names point at the same class instance
protocolA list of requirements. A struct or a class can adopt it

Switch

Every case is covered

switch pages {
case 0:
  print("empty")
case 1...300:
  print("short")
default:
  print("long")
}

Control rules

FormMeaning
switchMust be exhaustive. default covers what the other cases miss
No fall-throughA matching case ends the switch. fallthrough is how you continue
1...300A closed range. Both ends match
for book in booksWalks the values. The loop variable is a constant
guardThe happy path stays unindented. The else must leave the scope
breakLeaves a loop. A switch does not need it to avoid the next case

Throw and catch

A function that can fail

enum LoadError: Error {
  case missing
}
func load() throws -> String {
  throw LoadError.missing
}
do {
  let title = try load()
  print(title)
} catch {
  print("missing")
}

Error rules

FormResult
throwsThe function may throw. Callers must write try
do / catchHandles the error. error is in scope inside catch
try?Turns a failure into nil and drops the reason
try!Crashes when the call throws
deferRuns when the scope exits, including a return or a throw. Later defers run first
OverflowInt addition that does not fit is a trap, not a thrown error. &+ wraps. addingReportingOverflow reports it

References

A weak owner

class Reader {
  var name: String
  init(name: String) { self.name = name }
}
class Shelf {
  weak var owner: Reader?
}

Who keeps the object

WordEffect
ARCA class stays alive while a strong reference points at it. Structs are not reference-counted
StrongThe default. Two objects that each store the other stay alive forever
weakDoes not keep the object. The property is optional and becomes nil when the object is gone
unownedDoes not keep the object and is not optional. Using it after release crashes
[weak self]A closure capture list. Use it when the closure is stored on self
Value typesA struct, an array, and a string copy. A cycle needs two class references

Async and actors

Suspend, then continue

func fetchTitle() async -> String {
  return "Dune"
}
func show() async {
  let title = await fetchTitle()
  print(title)
}

Concurrency rules

PieceMeaning
asyncThe function may suspend. Call it with await
awaitA suspension point. Other work can run before the line continues
TaskStarts async work from synchronous code
actorProtects its mutable state. Outside calls are await
@MainActorRuns on the main actor. UI updates belong here
Swift 6 modeOpt-in. A shared var that any thread can touch becomes a compiler error. Prefer let, or isolate the value

Interview traps

Traps worth memorising

TrapWhat happensPrefer
title! when title is nilThe program stopsif let, guard let, or ??
books[9] on a short arrayA trap. Array lookup is not optionalCheck count, or books.indices.contains(9)
title[0]A string is not indexed by Inttitle.startIndex, then distance(from:to:) for an integer position
Int.max + 1A trap. catch does not see itaddingReportingOverflow, or &+ when wrapping is intended
Assigning a class and editing one nameBoth names see the editA struct when the copy should stay independent
A method that sets self.pages on a structDoes not compileMark the method mutating
A closure stored on a class that uses selfA retain cycle[weak self]
== on two class instancesCompares values only if you wrote Equatable. It does not mean the same object=== for identity
try?The error becomes nildo / catch when the reason matters
Expecting the next case to runSwift does not fall throughfallthrough when that is what you want
A global var in Swift 6 modeCompiler error. The variable is shared mutable statelet, or an actor
A public struct sent across actorsNot implicitly SendableAn explicit Sendable conformance when every field is safe to share

This stops on nil

let title: String? = nil
print(title!)

The first character

let title = "Dune"
let index = title.startIndex
print(title[index])

How to use this page: run swift hello.swift, keep title as a let, and unwrap published with if let before you print it. Then make Book a struct, and call an async function with await.