Swift is a statically typed, compiled, multi-paradigm programming language created by Apple that replaces Objective-C for iOS, macOS, watchOS, and visionOS development — providing optionals for null safety, value semantics, protocol-oriented programming, async/await with actors, and ARC memory management with no garbage collector.
📑 Swift Reference — All Topics
Optional chaining, nil coalescing, type inference, enums.
Protocol-oriented design, associated types, where clauses.
async/await, actors, retain cycles, weak references.
[Wireframe — content coming soon.]
[Wireframe — content coming soon.]
[Wireframe — content coming soon.]
[Wireframe — content coming soon.]
[Wireframe — content coming soon.]
[Wireframe — content coming soon.]
[Wireframe — content coming soon.]
[Wireframe — content coming soon.]
[Wireframe — content coming soon.]
[Wireframe — content coming soon.]
[Wireframe — content coming soon.]
[Wireframe — content coming soon.]
[Wireframe — content coming soon.]
[Wireframe — content coming soon.]
[Wireframe — content coming soon.]
[Wireframe — content coming soon.]
[Wireframe — content coming soon.]
[Wireframe — content coming soon.]
[Wireframe — content coming soon.]
[Wireframe — content coming soon.]
[Wireframe — content coming soon.]
[Wireframe — content coming soon.]
[Wireframe — content coming soon.]
[Wireframe — content coming soon.]
[Wireframe — content coming soon.]
[Wireframe — content coming soon.]
[Wireframe — content coming soon.]
Swift is Apple's replacement for Objective-C — modern, safe, fast, and expressive, designed to make iOS and macOS development productive while compiling to native code with C-level performance.
What Swift is
Swift is a statically typed, compiled, multi-paradigm programming language created by Chris Lattner at Apple, introduced at WWDC 2014 and open-sourced in December 2015. Swift was designed to replace Objective-C for Apple platform development — eliminating its verbose syntax and unsafe patterns while maintaining full interoperability with existing Objective-C codebases. Swift compiles to native machine code via LLVM (the same backend as Clang), achieving performance comparable to C. Swift is the required language for modern iOS, macOS, watchOS, tvOS, and visionOS development.
Swift is also used for server-side development (via Swift on Server / Vapor framework) and is the implementation language for several Apple system components. As of Swift 5.5 (2021), Swift is open-source and runs on Linux and Windows in addition to Apple platforms.
import Foundation
// Constants and variables
let name = "Priya" // let = constant (like val in Kotlin)
var count = 0 // var = variable
let pi: Double = 3.14159 // explicit type annotation
// String interpolation
print("Hello, \(name)!")
// Type inference
let city = "Mumbai" // inferred as String
let scores = [95, 88, 72] // inferred as [Int]
// Optional — the Swift way to handle nil
var nickname: String? = nil
print(nickname ?? "no nickname") // nil coalescing
// If let — safe unwrapping
if let n = nickname {
print("Nickname: \(n)")
} else {
print("No nickname set")
}
// Guard — early exit pattern
func greet(name: String?) {
guard let name = name else {
print("No name given"); return
}
print("Hello, \(name)!")
}Optionals — Swift's null safety
In Swift, every type is non-optional by default. To allow nil, you append ? to make it an Optional: String? is either a String value or nil. You must explicitly unwrap optionals before using the value. This eliminates null pointer crashes at compile time — if you don't handle the optional, the code won't compile.
var name: String? = "Priya"
// 1. Optional binding (safe unwrap)
if let n = name {
print(n.uppercased()) // only runs if name is not nil
}
// 2. Guard let — unwrap or return early
func process(value: String?) {
guard let v = value else { return }
print(v.count) // v is guaranteed non-nil here
}
// 3. Nil coalescing — provide a default
let display = name ?? "Anonymous"
// 4. Optional chaining — access properties safely
let length = name?.count // Int? (nil if name is nil)
// 5. Force unwrap — only when CERTAIN not nil
let forced = name! // crashes with fatal error if nil
// 6. Optional map (functional style)
let upper = name.map { $0.uppercased() } // String?Structs, classes, and enums
Swift has both structs and classes but with a crucial distinction: structs are value types (copied on assignment) and classes are reference types (shared on assignment). Most Swift standard library types — including String, Array, and Dictionary — are structs. Apple's Swift style guide recommends preferring structs over classes because value semantics eliminate whole categories of bugs caused by shared mutable state.
// Struct — value type (copied on assignment)
struct Point {
var x: Double
var y: Double
func distance() -> Double {
return (x*x + y*y).squareRoot()
}
}
var p1 = Point(x: 3, y: 4)
var p2 = p1 // p2 is an independent COPY
p2.x = 10 // does not affect p1
print(p1.x) // 3.0
// Enum with associated values (algebraic data type)
enum Result<T> {
case success(T)
case failure(String)
}
func divide(_ a: Double, by b: Double) -> Result<Double> {
guard b != 0 else { return .failure("Division by zero") }
return .success(a / b)
}
// Pattern matching with switch
switch divide(10, by: 2) {
case .success(let value): print("Result: \(value)")
case .failure(let error): print("Error: \(error)")
}Protocols
A protocol defines a contract — a set of methods and properties a conforming type must implement. Swift's protocol system is central to the language's design. Protocols can have default implementations via protocol extensions (similar to Kotlin's extension functions). Swift uses protocol-oriented programming as an alternative to class inheritance — "favour protocols over superclasses."
protocol Describable {
var description: String { get }
func describe() // required
}
// Default implementation via protocol extension
extension Describable {
func describe() {
print(description) // default — types can override
}
}
struct Car: Describable {
let make: String
let model: String
var description: String { "\(make) \(model)" }
}
struct Person: Describable {
let name: String
var description: String { "Person: \(name)" }
}
let items: [any Describable] = [Car(make:"Toyota", model:"Camry"), Person(name:"Priya")]
items.forEach { $0.describe() }Value types vs. reference types: why it matters
Swift's type system draws a sharp line between value semantics (structs, enums) and reference semantics (classes). When you assign or pass a struct, the entire value is copied — each variable has its own independent data. When you assign a class, only the reference is copied — both variables point to the same object. This distinction matters enormously for correctness: a function that modifies a struct parameter affects only its local copy; a function that modifies a class instance affects every reference to that object. Apple's frameworks (SwiftUI especially) are built heavily on value types and Copy-on-Write (CoW) optimisation — actual copying is deferred until mutation, so most copies are O(1).
Swift Concurrency: async/await and actors
Swift 5.5 (2021) introduced first-class concurrency: async/await, Task, TaskGroup, and actors. An actor is a reference type that serialises access to its mutable state — only one task can access actor state at a time, eliminating data races at compile time. The Swift compiler performs actor isolation checking — it is a compile error to access actor-isolated state from outside the actor without await. @MainActor marks code that must run on the main thread (UI updates).
import Foundation
// Async function
func fetchUser(id: Int) async throws -> String {
try await Task.sleep(nanoseconds: 100_000_000) // 0.1s
return "User\(id)"
}
// Structured concurrency — parallel tasks
func fetchAll() async throws {
async let user1 = fetchUser(id: 1)
async let user2 = fetchUser(id: 2)
let (u1, u2) = try await (user1, user2) // run in parallel
print("\(u1) and \(u2)")
}
// Actor — safe shared mutable state
actor Counter {
private var count = 0
func increment() { count += 1 }
func value() -> Int { count }
}
// Usage
Task {
let counter = Counter()
await counter.increment()
print(await counter.value())
}
// @MainActor — guarantees UI thread
@MainActor
func updateLabel(text: String) {
// label.text = text — safe: always on main thread
}Generics and opaque types
Swift generics are fully reified — the compiler generates specialised code per type. Swift 5.7 (2022) added primary associated types and simplified protocol use with some (opaque type) and any (existential type). some View means "some specific conforming type, chosen by the callee" — the compiler knows the concrete type at compile time. any View means "any type conforming to View" — dynamic dispatch at runtime. SwiftUI's body: some View is the canonical use of opaque types.
// Generic function
func swap<T>(_ a: inout T, _ b: inout T) {
let temp = a; a = b; b = temp
}
// Generic struct with constraint
struct Pair<T: Comparable> {
let first: T
let second: T
var min: T { first < second ? first : second }
}
// some — opaque return type (compiler knows concrete type)
func makeShape() -> some Shape {
return Circle(radius: 5) // caller gets a Shape but not the concrete type
}
// any — existential (dynamic dispatch)
func printShape(_ shape: any Shape) {
print(shape.area())
}
// Protocol with associated type
protocol Container {
associatedtype Element
func add(_ item: Element)
func all() -> [Element]
}SwiftUI and the declarative UI paradigm
SwiftUI (introduced 2019) is Apple's modern UI framework built on Swift's type system. Views are structs conforming to the View protocol. UI is described declaratively — you describe what the UI should look like given the current state, and SwiftUI handles the rendering and diffing. State is managed with property wrappers: @State (local view state), @StateObject/@ObservedObject (reference type state), @Binding (two-way binding), @EnvironmentObject (injected dependency). SwiftUI previews compile and render instantly in Xcode.
var p2 = p1 where p1 is a struct: p2 is an independent copy. Where p1 is a class: p2 is another reference to the same object. Mutating p2 (struct) leaves p1 unchanged. Mutating p2 (class) changes what p1 sees too. Swift structs are default; use classes when identity and shared mutation are needed.! force-unwrap will crash, not return nil. name! on a nil Optional crashes with "Unexpectedly found nil while unwrapping an Optional value." Use if let, guard let, or ?? for safe unwrapping. Force-unwrap only when you have a compile-time guarantee the value exists (e.g. IBOutlets after viewDidLoad).Swift's memory model: ARC and weak references
Swift uses Automatic Reference Counting (ARC) for memory management — not a tracing garbage collector. ARC inserts retain and release calls at compile time (not runtime). When a class instance's reference count drops to zero, it is immediately deallocated. ARC is deterministic — deallocation happens at a known point, not at some future GC pause. However, ARC cannot automatically resolve reference cycles: if object A holds a strong reference to B and B holds a strong reference to A, neither will ever be deallocated. The fix: weak references (automatically becomes nil when the object is deallocated) and unowned references (crash if accessed after deallocation, like !). Closures that capture self must use [weak self] or [unowned self] capture lists to break cycles.
The Swift compiler and LLVM
Swift is compiled by the Swift compiler (swiftc) which uses LLVM as its backend. The frontend performs parsing, semantic analysis, type checking, and Swift Intermediate Language (SIL) generation. SIL is a high-level IR that enables Swift-specific optimisations: devirtualisation, generic specialisation, and ARC optimisation (coalescing retain/release pairs, eliminating redundant retains). SIL then lowers to LLVM IR, where standard LLVM optimisation passes run. The whole-module optimisation mode (-O whole-module) allows the compiler to see and optimise across all source files simultaneously.
Swift evolution and ABI stability
Swift's evolution process (Swift Evolution, github.com/apple/swift-evolution) governs language changes through a proposal system. Swift 5.0 (March 2019) achieved ABI stability — binary compatibility between Swift modules compiled with different compiler versions on Apple platforms. Before Swift 5, every app had to bundle its own copy of the Swift runtime. After ABI stability, the Swift runtime is part of the OS (iOS 12.2+, macOS 10.14.4+), reducing app binary sizes. Swift 5.9 (2023) added macros — compile-time code generation.
Apple Inc. The Swift Programming Language. docs.swift.org/swift-book/. — Authoritative language reference. Apple Inc. Swift API Design Guidelines. swift.org/documentation/api-design-guidelines/. Swift Evolution proposals: github.com/apple/swift-evolution. Lattner, C. "Swift's origin." chris.lattner.com/swift-origin.html.