App Development with Swift study materials
App Development with Swift study resources

App Development with Swift cheat sheet

App Development with Swift · Keep the key ideas within reach.

Quick reference

Swift Language Fundamentals

  • let binds a value once and cannot be reassigned; var is mutable. The type is fixed at compile time in both cases and is inferred from the initializer when no annotation is written.

  • Integer literals default to Int and floating-point literals to Double; no implicit numeric conversion exists, so Int(3.9) truncates toward zero and mixed-type arithmetic requires explicit conversions.

  • Structures, enumerations, and tuples are value types copied on assignment and argument passing; classes are reference types, so copies of a reference share one instance.

  • === and !== compare class instance identity; == requires Equatable conformance and compares values. Identity operators cannot be applied to value types.

  • String interpolation \(expr) inserts any value into a literal; multi-line literals use triple double quotes, and text inside double-quoted single hash delimiters turns off interpolation and escape processing.

  • T? is shorthand for Optional<T>, and nil is assignable only to optional types. Any holds values of any type while AnyObject holds class instances.

  • Access levels, narrowest first: private (enclosing declaration and same-file extensions), fileprivate, internal (the default, whole module), public, and open (public plus subclassable and overridable outside the module).

  • typealias gives an existing type a second name and creates no new type, so the alias and the original type are interchangeable everywhere.

  • Range operators: a...b is closed, a..<b is half-open, and a... or ...a is one-sided; ranges and the ~= operator back the pattern matching used by switch cases.

Quick reference

Control Flow, Functions, and Closures

  • switch must be exhaustive over the matched type, performs no implicit fallthrough, and supports range, tuple, and where-clause patterns; the fallthrough keyword continues execution into the next case body.

  • guard requires its else block to exit scope via return, break, continue, throw, or a Never-returning call, and names bound by guard let stay visible for the rest of the enclosing scope.

  • A parameter's internal name doubles as its external argument label; an underscore before the name removes the label, and a default value makes that argument omittable at the call site.

  • Variadic parameters such as Int... collect zero or more arguments into an array; inout parameters mutate the caller's variable, which must be passed with an ampersand prefix.

  • stride(from:to:by:) excludes the end value while stride(from:through:by:) includes it; repeat-while evaluates its condition after the body, guaranteeing at least one iteration.

  • Closures use the form { (parameters) -> ReturnType in statements }; $0, $1 are shorthand parameter names, and a trailing closure may be written after the call parentheses.

  • Closures are non-escaping by default and may not outlive the call; @escaping is required for stored or delayed execution, as with completion handlers.

  • Closures capture referenced variables rather than copies of them; a capture list such as [weak self] or [unowned self] changes ownership and breaks retain cycles.

  • defer blocks run at scope exit in reverse order of their declaration, on every exit path including a thrown error.

Quick reference

Data Modeling with Structures, Classes, Enumerations, and Protocols

  • A structure with no custom initializer receives a synthesized memberwise initializer covering all stored properties in declaration order; classes never receive a memberwise initializer.

  • Struct and enum methods that assign to stored properties must be marked mutating, because self is immutable inside non-mutating methods of value types.

  • Class initialization runs in two phases: every stored property must be initialized before self is used or an instance method is called, and convenience initializers delegate with self.init.

  • deinit exists only on classes and runs automatically when the final strong reference is released; a required init forces every subclass to implement that initializer.

  • Enumeration cases may carry associated values extracted by case let .name(value) in a switch; declaring a raw type gives each case a rawValue and a failable init?(rawValue:).

  • CaseIterable synthesizes allCases only when no case has associated values, and indirect marks an enumeration whose cases recursively contain the enumeration itself.

  • Protocol extensions supply default implementations of requirements; members declared only in an extension are dispatched statically rather than through dynamic polymorphism.

  • Equatable, Hashable, and Codable are synthesized when every stored property conforms, and Identifiable requires an id property.

  • some P is an opaque concrete type chosen by the callee while any P is an existential box; protocol composition A & B requires both. final blocks subclassing and static blocks overriding.

Quick reference

Collections, Optionals, and Error Handling

  • Array is ordered and indexed by Int; Dictionary maps Hashable keys to values with no guaranteed order; Set stores unique Hashable elements with no guaranteed order.

  • All three standard collections have value semantics: assignment or parameter passing copies the collection, so mutating the copy leaves the original unchanged.

  • Subscripting a dictionary with a key returns an optional that is nil for a missing key; assigning nil through that subscript removes the key-value pair.

  • map preserves element count; compactMap discards nil results and returns non-optionals; flatMap concatenates nested sequences; reduce and reduce(into:) fold to a single value.

  • sorted() returns a new array while sort() mutates in place; filter returns a new collection, and first(where:) and firstIndex(of:) return optionals.

  • try marks a throwing call; do/catch handles errors, and a non-throwing function must handle or propagate them. try? gives nil on failure, while try! traps at runtime.

  • Custom error types conform to Error, most often as an enumeration whose cases describe each failure, and catch clauses match those cases by pattern.

  • Optional binding with if let or guard let shadows the original name; if case let and guard case match enum cases carrying associated values without a full switch.

  • ?? unwraps an optional or substitutes a default; chained access with ?. short-circuits to nil at the first missing link and always produces an optional result.

Quick reference

User Interfaces and App Architecture

  • SwiftUI views are value types conforming to View whose body returns some View; a state change re-evaluates body, and the framework diffs the result against the previous hierarchy.

  • @State owns view-local mutable storage that persists across body updates; @Binding references state owned by an ancestor and allows two-way writes, passed with the $ prefix.

  • @StateObject creates and owns an ObservableObject for the view's lifetime; @ObservedObject only observes an instance owned elsewhere; @EnvironmentObject reads an object injected by an ancestor.

  • @Published properties on an ObservableObject announce changes and trigger view updates; mutating them from a background thread requires handing the work back to the main thread.

  • The app entry point is a type marked @main: an App with a WindowGroup scene in SwiftUI, or a UIApplicationDelegate paired with a SceneDelegate in UIKit.

  • UIKit lifecycle order: viewDidLoad once, then viewWillAppear, viewDidAppear, viewWillDisappear, viewDidDisappear; viewWillLayoutSubviews and viewDidLayoutSubviews wrap each layout pass.

  • Programmatic Auto Layout requires setting translatesAutoresizingMaskIntoConstraints to false before activating constraints, otherwise the generated autoresizing constraints conflict.

  • All interface updates occur on the main thread, so background results return through @MainActor, MainActor.run, or DispatchQueue.main.async; @IBOutlet and @IBAction connect storyboard objects to code.

  • NavigationStack pushes screens via NavigationLink or navigationDestination, and List needs Identifiable rows or an explicit id key path to track identity.