Swift cheatsheet – syntax overview
71 key commands and patterns for quick reference.
Basics Types & operators Optionals Control flow Functions & closures Collections Structs, classes & enums Protocols, extensions & generics Errors & concurrency Tools & SwiftUI
Basics
print("Text \(wert)", x, y) | Output with string interpolation |
let x = 5 | Constant (immutable) |
var y = 5 | Variable (mutable) |
let z: Double = 5 | Specify the type explicitly |
// Comment /* Block */ /// Doc | Comments |
Double(x) Int(y) String(z) | Explicit type conversion |
type(of: x) | Determine the type of a value |
Types & operators
Int Double Float Bool String Character | Basic types |
+ - * / % | Arithmetic (Int division truncates) |
== != < > <= >= | Comparisons |
&& || ! | Logical operators |
a ?? b | Nil-coalescing: a, otherwise b |
1...5 1..<5 ...5 5... | Ranges (closed, half-open, one-sided) |
x &+ y | Addition with overflow (wrap-around) |
Optionals
var x: Int? = nil | Declare an optional |
if let v = x { } | Unwrap safely |
guard let v = x else { return } | Unwrap or leave early |
x ?? 0 | Default value on nil |
x?.methode() | Optional chaining |
x! | Force unwrap (crash on nil) |
x.map { $0 + 1 } | Transform the content if present |
Control flow
if a > b { } else if a == b { } else { } | Branching |
x > 0 ? "pos" : "neg" | Ternary operator |
switch x { case 1...5: ... default: ... } | switch with ranges (exhaustive, no fallthrough) |
for i in 0..<5 { } | Loop over 0..4 |
for (i, x) in liste.enumerated() { } | Index and value |
while bedingung { } repeat { } while bedingung | Loops with a condition |
break continue aussen: for ... | Break, continue, label for nested loops |
Functions & closures
func f(_ a: Int, b: Int = 2) -> Int { a + b } | Function with label control and a default value |
func f(_ z: Int...) { } | Variadic parameter |
func f(_ x: inout Int) f(&v) | inout: modify the caller's variable |
func f() -> (min: Int, max: Int) | Tuple as return value |
{ (x: Int) -> Int in x * 2 } | Closure written out in full |
liste.map { $0 * 2 } | Shorthand with $0 |
func f(_ h: @escaping () -> Void) | Closure that outlives the function |
Collections
var a = [1, 2, 3] | Create an array |
a.append(4) a.insert(0, at: 0) a.remove(at: 1) | Adding and removing |
a.count a.isEmpty a.first a.last | Size and edge elements (first/last are optionals) |
a.sorted() a.sort() a.reversed() | Sort (new / in place), reverse |
a.map { } a.filter { } a.reduce(0, +) | Transform, filter, aggregate |
var d = ["a": 1] d["b"] = 2 d["c", default: 0] | Create a dictionary, set, read with a default |
for (k, v) in d { } | Iterate over a dictionary |
Set([1, 2, 2]) a.union(b) a.intersection(b) | Sets and set operations |
Structs, classes & enums
struct P { var x: Int } | Value type (copied), memberwise init included |
class K { var x = 0 } | Reference type (shared) |
mutating func f() { } | Struct method that modifies itself |
var flaeche: Double { b * h } | Computed property |
var x = 0 { didSet { } } | Property observer |
enum E { case a, b(Int), c(name: String) } | Enum with associated values |
class B: A { override func f() { } } | Inheritance and overriding (classes only) |
Protocols, extensions & generics
protocol P { var x: Int { get } func f() } | Define a protocol |
struct S: P { ... } | Adopt a protocol |
extension P { func g() { } } | Default implementation / extend a type |
func f<T: Comparable>(_ a: T) -> T | Generic function with a constraint |
some P any P | Opaque type / existential |
extension Array where Element: Numeric { } | Conditional extension |
Errors & concurrency
enum F: Error { case a } | Custom error type |
func f() throws -> Int | Function that can throw errors |
do { try f() } catch { print(error) } | Catch errors |
try? try! | Error to nil / crash on error |
defer { aufraeumen() } | Run when the block is left |
func f() async -> Int await f() | Define and call an asynchronous function |
async let x = f() await x | Start in parallel, collect later |
actor A { } @MainActor | Thread-safe state / main thread |
Tools & SwiftUI
swift datei.swift | Run a file as a script |
swiftc datei.swift -o prog | Compile to a binary |
swift package init --type executable | Create a new Swift package |
swift build swift run swift test | Build, run, test |
@State private var x = 0 | SwiftUI: state of a view |
TextField("Name", text: $name) | $ = binding (two-way connection) |
VStack { } HStack { } ZStack { } List { } | SwiftUI containers |