Skip to main content

Swift Reference

v1.0.0

Quick-reference for Swift syntax, types, optionals, closures, and SwiftUI patterns

Quick reference for Swift syntax including optionals, protocols, structured concurrency (async/await and actors), closures, and collections.

How to use
  • Browse categories or search for specific syntax (e.g. "guard let", "actor", "Codable") to jump to the entry.
  • Click entries to expand examples — copy the snippet and adapt it in your Swift project.
  • Use the category tabs to explore related concepts together (Optionals, Concurrency).
  • Try the Example picker (Simple → Advanced → Pro) to pre-fill a search for common patterns.

55 entries found

Variable
Data Types

var name: Type = value

Declare a mutable variable with an explicit or inferred type.

Constant
Data Types

let name: Type = value

Declare an immutable constant — value cannot change after assignment.

Int / Double / Float
Data Types

Int Double Float Int8 Int16 Int32 Int64 UInt

Numeric types: integers (signed and unsigned) and floating-point numbers.

String
Data Types

let s: String = "text"

Unicode string type. Supports interpolation with backslash-parentheses.

Bool
Data Types

let flag: Bool = true

Boolean type — either true or false.

Tuple
Data Types

let t: (T1, T2) = (v1, v2)

Group multiple values into a single compound value.

Type Alias
Data Types

typealias Name = ExistingType

Create an alternative name for an existing type.

Struct
Data Types

struct Name { var field: Type }

Value type with properties, methods, and memberwise initializer.

Enum
Data Types

enum Name { case a, b, c }

Define a type with a finite set of related values, optionally with associated data.

Class
Data Types

class Name { var prop: Type }

Reference type with inheritance, deinitializers, and reference counting.

Optional type
Optionals

var name: Type?

A value that may be nil — wraps any type in an Optional container.

Optional binding (if let)
Optionals

if let value = optional { ... }

Safely unwrap an optional — body executes only if non-nil.

Guard let
Optionals

guard let value = optional else { return }

Early exit if optional is nil — unwrapped value available after guard.

Nil coalescing
Optionals

optional ?? defaultValue

Provide a fallback value when the optional is nil.

Optional chaining
Optionals

value?.property?.method()

Access properties and methods on optional values — returns nil if any link is nil.

Force unwrap
Optionals

optional!

Force-extract the value — crashes at runtime if nil. Use only when certain.

Implicitly unwrapped
Optionals

var name: Type!

Optional that is automatically unwrapped on access — useful for late initialization.

if / else
Control Flow

if condition { } else if { } else { }

Conditional branching — parentheses around condition are optional.

switch
Control Flow

switch value { case pattern: ... }

Pattern matching — must be exhaustive, no implicit fallthrough.

for-in
Control Flow

for item in collection { }

Iterate over sequences, ranges, arrays, dictionaries.

while / repeat-while
Control Flow

while condition { } / repeat { } while condition

Loop while a condition is true. repeat-while checks after each iteration.

Range operators
Control Flow

a...b (closed) a..<b (half-open)

Closed range includes both endpoints; half-open excludes the upper bound.

where clause (loops)
Control Flow

for item in collection where condition { }

Filter loop iterations with a where clause.

Function
Functions & Closures

func name(param: Type) -> ReturnType { }

Define a named function with typed parameters and return value.

Default parameters
Functions & Closures

func name(param: Type = default) { }

Parameters can have default values — callers may omit them.

Argument labels
Functions & Closures

func name(label param: Type)

External argument label differs from internal parameter name. Use _ to omit the label.

Variadic parameters
Functions & Closures

func name(values: Type...)

Accept zero or more values of the same type, received as an array.

Closure expression
Functions & Closures

{ (params) -> Return in body }

Anonymous function (closure) that captures surrounding context.

Trailing closure
Functions & Closures

func(args) { closure body }

When the last parameter is a closure, write it after the parentheses.

@escaping
Functions & Closures

func name(handler: @escaping () -> Void)

Mark closures that outlive the function call (stored or called later).

Protocol
Protocols

protocol Name { func method() -> Type }

Define a blueprint of methods, properties, and requirements that conforming types must implement.

Protocol conformance
Protocols

struct Name: ProtocolName { ... }

A type adopts a protocol by implementing all its requirements.

Protocol extension
Protocols

extension ProtocolName { func defaultImpl() { } }

Provide default implementations for protocol methods.

Protocol composition
Protocols

func f(param: ProtocolA & ProtocolB)

Require a value to conform to multiple protocols at once.

Associated type
Protocols

protocol Name { associatedtype Item }

A placeholder type within a protocol — concrete type chosen by the conforming type.

Codable
Protocols

struct Name: Codable { ... }

Conform to Codable (Encodable + Decodable) for automatic JSON serialization.

async / await
Concurrency

func name() async -> Type { }

Declare and call asynchronous functions with structured concurrency.

Task
Concurrency

Task { await asyncWork() }

Create a task to run async code from a synchronous context.

TaskGroup
Concurrency

await withTaskGroup(of: T.self) { group in ... }

Run multiple async tasks concurrently and collect results.

Actor
Concurrency

actor Name { var state: Type }

Reference type that protects its mutable state from data races.

@MainActor
Concurrency

@MainActor func updateUI() { }

Ensure a function or class runs on the main thread (UI updates).

AsyncSequence
Concurrency

for await item in asyncSequence { }

Iterate over values produced asynchronously over time.

throw / throws
Error Handling

func name() throws -> Type { throw error }

Functions that can produce errors are marked throws — use throw to raise an error.

do-catch
Error Handling

do { try expr } catch { handle }

Handle errors from throwing functions with pattern matching on error types.

try?
Error Handling

let value = try? throwingExpr

Convert a throwing expression to an optional — nil on error.

try!
Error Handling

let value = try! throwingExpr

Force-try — crashes at runtime if the expression throws. Use only when failure is impossible.

Result type
Error Handling

Result<Success, Failure>

Represent either a success value or an error — useful for async callbacks.

Custom Error type
Error Handling

enum MyError: Error, LocalizedError { ... }

Define application-specific errors conforming to Error protocol.

Array
Collections

var arr: [Type] = [v1, v2, v3]

Ordered collection of values — zero-indexed, supports generics.

Dictionary
Collections

var dict: [Key: Value] = [k1: v1]

Unordered collection of key-value pairs — keys must be Hashable.

Set
Collections

var set: Set<Type> = [v1, v2]

Unordered collection of unique values — supports set algebra.

map / filter / reduce
Collections

.map { } .filter { } .reduce(init) { }

Functional transformations on sequences — chainable, lazy-compatible.

compactMap
Collections

.compactMap { transform }

Map and remove nil values in one step — useful for optional transformations.

flatMap
Collections

.flatMap { transform }

Map each element to a sequence and flatten the results into a single array.

Enumerated / zip
Collections

.enumerated() zip(seq1, seq2)

Pair elements with their index, or combine two sequences element-wise.