Swift Reference
Free reference guide: Swift Reference
About Swift Reference
The Swift Reference is a searchable quick-reference for the Swift programming language, organized into six categories: Basics, Types, Functions, Protocols, Optionals, and Concurrency. Each entry provides the syntax pattern, a clear description, and a copy-ready code example that compiles in Swift 5.x and later. Swift is Apple's primary language for iOS, macOS, watchOS, tvOS, and visionOS development, and is also used for server-side applications via frameworks like Vapor.
Swift combines the performance of a compiled language with the expressiveness of modern language features. Its type system enforces safety at compile time through optionals, value types (structs and enums), and protocol-oriented programming. This reference covers Swift-specific patterns including guard statements for early exit, pattern matching in switch with associated values, trailing closure syntax, the Codable protocol for JSON serialization, and the modern structured concurrency model with async/await, Task, TaskGroup, and actors.
Whether you are unwrapping optionals with if let or guard let, defining protocol extensions with default implementations, encoding structs to JSON with Codable, creating concurrent data fetches with async let, or protecting shared mutable state with actors, this cheat sheet gives you the exact syntax. It is designed for iOS developers, Swift beginners learning the language fundamentals, and experienced developers who need a quick reference during code reviews or pair programming sessions.
Key Features
- Basics covering let/var declarations, if/else conditionals, for-in loops, switch with pattern matching and ranges, guard for early exit, string interpolation, closures with trailing syntax, and tuples
- Type system including struct (value type) with methods, enum with associated values and raw values, typealias for complex type names, and Any/AnyObject for heterogeneous collections with type casting
- Functions with named and external parameter labels, default values, inout pass-by-reference parameters, variadic parameters, @discardableResult, and throws/try/catch error handling
- Protocol-oriented programming with protocol definitions, protocol extensions for default implementations, Codable for JSON encoding/decoding, and Equatable/Hashable conformance
- Optional handling including optional types, if let and guard let binding, optional chaining for nested access, nil coalescing operator (??), and map/flatMap transformations on optional values
- Modern structured concurrency with async/await functions, Task and Task.detached for spawning work, async let for parallel execution, TaskGroup for dynamic concurrency, and actor for thread-safe state isolation
- Searchable interface with category filtering, syntax-highlighted Swift code examples, and bilingual Korean/English content
- All examples follow Swift 5.x conventions and are compatible with Xcode projects, Swift Playgrounds, and server-side Swift environments
Frequently Asked Questions
What is the difference between let and var in Swift?
let declares an immutable constant whose value cannot be changed after initialization. var declares a mutable variable that can be reassigned. Swift encourages using let by default and only using var when mutation is necessary. The compiler will warn you if a var is never mutated, suggesting you change it to let. For reference types (classes), let means the reference cannot change, but the object properties can still be modified.
How do optionals work and why are they important?
Optionals represent a value that may or may not exist, declared with a ? suffix (e.g., String?). They force you to handle the nil case explicitly, preventing null pointer crashes common in other languages. You unwrap optionals safely with if let (conditional binding), guard let (early exit), optional chaining (?.), or the nil coalescing operator (??). Force unwrapping with ! should be avoided unless you are certain the value exists.
When should I use a struct vs a class in Swift?
Swift favors structs (value types) over classes (reference types). Use structs for data models, coordinates, configurations, and most types. Structs are copied on assignment, thread-safe by default, and benefit from compiler optimizations. Use classes when you need reference semantics (shared mutable state), inheritance, or Objective-C interoperability. Apple's own frameworks increasingly use structs, and SwiftUI views are all structs.
How does pattern matching work in Swift switch statements?
Swift switch statements are exhaustive (must cover all cases) and do not fall through by default. They support matching enum cases with associated values, ranges (case 1...10), tuples, where clauses, and value binding (case let x where x > 0). Each case can bind associated values: case .success(let data) extracts the data. The default case handles any remaining possibilities.
What is protocol-oriented programming in Swift?
Protocol-oriented programming uses protocols and protocol extensions as the primary mechanism for code reuse, instead of class inheritance. You define behavior contracts with protocols, provide default implementations via extensions, and compose functionality by conforming to multiple protocols. This avoids the fragile base class problem and supports value types. Key examples include Codable (combining Encodable and Decodable) and Equatable/Hashable for automatic synthesis.
How do async/await and structured concurrency work?
Functions marked with async can suspend execution at await points without blocking threads. Call them with try await inside other async contexts. Use Task { } to bridge from synchronous to asynchronous code. async let enables parallel execution of multiple async operations. TaskGroup provides dynamic task spawning with for await iteration over results. All tasks follow structured concurrency: child tasks are automatically cancelled when the parent scope exits.
What are actors and when should I use them?
Actors are reference types that protect their mutable state from concurrent access. Properties and methods inside an actor are isolated: external callers must use await to access them, ensuring one-at-a-time execution. Use actors when multiple tasks need to read and write shared state. The @MainActor attribute marks code that must run on the main thread, which is essential for UI updates in SwiftUI and UIKit.
How does Codable JSON encoding and decoding work?
Conforming a struct or class to Codable (which combines Encodable and Decodable) enables automatic JSON serialization. Use JSONEncoder().encode(value) to convert to Data and JSONDecoder().decode(Type.self, from: data) to parse JSON. Custom key mapping is done via CodingKeys enum. Nested types must also be Codable. For dates, configure encoder.dateEncodingStrategy. This replaces manual JSON parsing and third-party libraries like SwiftyJSON for most use cases.