Swift Reference
v1.0.0Quick-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
var name: Type = value
Declare a mutable variable with an explicit or inferred type.
let name: Type = value
Declare an immutable constant — value cannot change after assignment.
Int Double Float Int8 Int16 Int32 Int64 UInt
Numeric types: integers (signed and unsigned) and floating-point numbers.
let s: String = "text"
Unicode string type. Supports interpolation with backslash-parentheses.
let flag: Bool = true
Boolean type — either true or false.
let t: (T1, T2) = (v1, v2)
Group multiple values into a single compound value.
typealias Name = ExistingType
Create an alternative name for an existing type.
struct Name { var field: Type }
Value type with properties, methods, and memberwise initializer.
enum Name { case a, b, c }
Define a type with a finite set of related values, optionally with associated data.
class Name { var prop: Type }
Reference type with inheritance, deinitializers, and reference counting.
var name: Type?
A value that may be nil — wraps any type in an Optional container.
if let value = optional { ... }
Safely unwrap an optional — body executes only if non-nil.
guard let value = optional else { return }
Early exit if optional is nil — unwrapped value available after guard.
optional ?? defaultValue
Provide a fallback value when the optional is nil.
value?.property?.method()
Access properties and methods on optional values — returns nil if any link is nil.
optional!
Force-extract the value — crashes at runtime if nil. Use only when certain.
var name: Type!
Optional that is automatically unwrapped on access — useful for late initialization.
if condition { } else if { } else { }
Conditional branching — parentheses around condition are optional.
switch value { case pattern: ... }
Pattern matching — must be exhaustive, no implicit fallthrough.
for item in collection { }
Iterate over sequences, ranges, arrays, dictionaries.
while condition { } / repeat { } while condition
Loop while a condition is true. repeat-while checks after each iteration.
a...b (closed) a..<b (half-open)
Closed range includes both endpoints; half-open excludes the upper bound.
for item in collection where condition { }
Filter loop iterations with a where clause.
func name(param: Type) -> ReturnType { }
Define a named function with typed parameters and return value.
func name(param: Type = default) { }
Parameters can have default values — callers may omit them.
func name(label param: Type)
External argument label differs from internal parameter name. Use _ to omit the label.
func name(values: Type...)
Accept zero or more values of the same type, received as an array.
{ (params) -> Return in body }
Anonymous function (closure) that captures surrounding context.
func(args) { closure body }
When the last parameter is a closure, write it after the parentheses.
func name(handler: @escaping () -> Void)
Mark closures that outlive the function call (stored or called later).
protocol Name { func method() -> Type }
Define a blueprint of methods, properties, and requirements that conforming types must implement.
struct Name: ProtocolName { ... }
A type adopts a protocol by implementing all its requirements.
extension ProtocolName { func defaultImpl() { } }
Provide default implementations for protocol methods.
func f(param: ProtocolA & ProtocolB)
Require a value to conform to multiple protocols at once.
protocol Name { associatedtype Item }
A placeholder type within a protocol — concrete type chosen by the conforming type.
struct Name: Codable { ... }
Conform to Codable (Encodable + Decodable) for automatic JSON serialization.
func name() async -> Type { }
Declare and call asynchronous functions with structured concurrency.
Task { await asyncWork() }
Create a task to run async code from a synchronous context.
await withTaskGroup(of: T.self) { group in ... }
Run multiple async tasks concurrently and collect results.
actor Name { var state: Type }
Reference type that protects its mutable state from data races.
@MainActor func updateUI() { }
Ensure a function or class runs on the main thread (UI updates).
for await item in asyncSequence { }
Iterate over values produced asynchronously over time.
func name() throws -> Type { throw error }
Functions that can produce errors are marked throws — use throw to raise an error.
do { try expr } catch { handle }
Handle errors from throwing functions with pattern matching on error types.
let value = try? throwingExpr
Convert a throwing expression to an optional — nil on error.
let value = try! throwingExpr
Force-try — crashes at runtime if the expression throws. Use only when failure is impossible.
Result<Success, Failure>
Represent either a success value or an error — useful for async callbacks.
enum MyError: Error, LocalizedError { ... }
Define application-specific errors conforming to Error protocol.
var arr: [Type] = [v1, v2, v3]
Ordered collection of values — zero-indexed, supports generics.
var dict: [Key: Value] = [k1: v1]
Unordered collection of key-value pairs — keys must be Hashable.
var set: Set<Type> = [v1, v2]
Unordered collection of unique values — supports set algebra.
.map { } .filter { } .reduce(init) { }
Functional transformations on sequences — chainable, lazy-compatible.
.compactMap { transform }
Map and remove nil values in one step — useful for optional transformations.
.flatMap { transform }
Map each element to a sequence and flatten the results into a single array.
.enumerated() zip(seq1, seq2)
Pair elements with their index, or combine two sequences element-wise.