Skip to content
AgileLogics

Swift Cheat Sheet

Learn Swift from the basics →

Constants, Variables & Types

let name = "Ada"
Constant — can't be changed (prefer by default)
var score = 0
Variable — can be changed
let price: Double = 9.99
Explicit type annotation
Int, Double, String, Bool, Character
Core types
Int("42") / String(42) / Double(7)
Conversion (Int(_:) from a String returns an optional)

Strings

"Hello, \(name)!"
String interpolation
s.count / s.isEmpty
Length / emptiness
s.uppercased() / s.lowercased()
Change case
s.hasPrefix("He") / s.contains("ll")
Prefix / substring check
s.split(separator: ",")
Split into substrings
let text = """ ... """
Multi-line string literal (the quotes go on their own lines)

Optionals

var email: String? = nil
A value that may be missing
if let email { print(email) }
Unwrap if present
guard let user else { return }
Unwrap or exit early
let name = input ?? "Guest"
Default value (nil-coalescing)
user?.address?.city
Optional chaining

Control Flow

if x > 0 { } else if x < 0 { } else { }
Conditional
let letter = switch grade { case 90...: "A"; case 80..<90: "B"; default: "C" }
Exhaustive switch expression with ranges (Swift 5.9+)
for i in 1...5 { }
Closed range loop (1 to 5)
for i in 0..<count { }
Half-open range (excludes count)
while cond { } / repeat { } while cond
While loops

Collections

var nums = [1, 2, 3]
Array
nums.append(4)
Add to an array
var ages = ["ada": 36]
Dictionary
ages["bob", default: 0]
Lookup with a default
let tags: Set = ["swift", "ios"]
Set (unique values)
nums.map { $0 * 2 }.filter { $0 > 2 }
Transform and filter
nums.reduce(0, +)
Combine into one value

Functions & Closures

func greet(_ name: String, from city: String = "Oslo") -> String
Labels, default parameter, return type
func swapValues(_ a: inout Int, _ b: inout Int)
In-out parameters (call with &x)
let double = { (n: Int) -> Int in n * 2 }
Closure
names.sorted { $0 < $1 }
Trailing closure with shorthand arguments

Types

struct Point { var x = 0.0, y = 0.0 }
Struct (value type)
final class Account { }
Class (reference type)
enum Result { case success(Int), failure(String) }
Enum with associated values
protocol Shape { var area: Double { get } }
Protocol
extension Int { var isEven: Bool { self % 2 == 0 } }
Extension
func largest<T: Comparable>(_ a: T, _ b: T) -> T
Generic function

Errors & Concurrency

enum LoginError: Error { case wrongPassword }
Define an error
func login() throws -> User
A throwing function
do { let user = try login() } catch { print(error) }
Handle errors
func load() async throws -> Data
Asynchronous function
let data = try await load()
Call and wait
actor Counter { var value = 0 }
Actor — protects its state from data races

Tooling

swift hello.swift
Run a single file
swift package init --type executable
Create a package
swift build / swift run
Build / build and run
swift test
Run the package's tests