Start a project

Swift A–Z · 27 terms

Swift references A–F

Explore an A-F directory of essential Swift terms. Each entry delivers clear definitions, practical code examples, and usage tips tailored for iOS and watchOS developers. This reference empowers you to master Swift’s nuances quickly, with balanced coverage across letters for consistent depth.

A

Actor

An actor is a reference type that protects its mutable state from concurrent access, ensuring thread-safety in concurrent programming.

actor Counter {
    var value: Int = 0
    func increment() {
        value += 1
    }
}

Usage tip: Use actors in iOS apps for managing shared state in background tasks, like updating UI data from network calls on watchOS.

Any

Any is a type that can represent an instance of any type, including function types and class types.

let mixedArray: [Any] = [1, "two", 3.0]

Usage tip: Ideal for heterogeneous collections in SwiftUI views, but type-cast carefully to avoid runtime errors in watchOS data handling.

Array

An Array is an ordered collection of values of the same type, resizable and mutable.

var fruits: [String] = ["Apple", "Banana"]
fruits.append("Cherry")

Usage tip: Use arrays for list data in SwiftUI List views on iOS, optimizing for watchOS by keeping them lightweight to prevent scroll lag.

Async/Await

Async/await is a syntax for writing asynchronous code in a synchronous style, improving readability.

func fetchData() async throws -> Data {
    let url = URL(string: "https://example.com")!
    let (data, _) = try await URLSession.shared.data(from: url)
    return data
}

Usage tip: Integrate with SwiftUI tasks for fetching remote data in iOS views; on watchOS, use for efficient background syncing without blocking the UI.

Associatedtype

Associatedtype declares a placeholder type in a protocol, to be defined by conforming types.

protocol Container {
    associatedtype Item
    var count: Int { get }
}

Usage tip: Useful in generic SwiftUI components for type-safe data models, enhancing reusability in iOS and watchOS apps.

B

Bool

Bool is a value type representing true or false.

let isActive: Bool = true

Usage tip: Control SwiftUI view states, like toggling visibility in iOS toggles or watchOS complications.

Break

Break terminates the execution of a loop or switch statement.

for i in 1...10 {
    if i == 5 { break }
    print(i)
}

Usage tip: Use in data processing loops for early exits in iOS background tasks, conserving battery on watchOS.

Button

Button is a SwiftUI view that triggers an action when tapped.

Button("Tap Me") {
    print("Button tapped")
}

Usage tip: Style for iOS with modifiers; on watchOS, ensure large tap targets for usability on small screens.

C

Class

Class is a reference type that supports inheritance and deinitialization.

class Vehicle {
    var speed: Int = 0
}

Usage tip: Model shared objects in SwiftUI observable classes for iOS state management; avoid heavy use on watchOS for performance.

Closure

A closure is a self-contained block of functionality that can be passed around.

let greet = { print("Hello") }
greet()

Usage tip: Use in SwiftUI animations or completions; capture lists prevent retain cycles in iOS and watchOS.

Codable

Codable is a protocol for types that can be encoded and decoded to/from external representations like JSON.

struct User: Codable {
    var name: String
}

Usage tip: Serialize models for iOS network requests; on watchOS, for storing user data in UserDefaults.

Continue

Continue skips the rest of the current loop iteration and starts the next.

for i in 1...5 {
    if i % 2 == 0 { continue }
    print(i)
}

Usage tip: Filter data in loops for SwiftUI list population on iOS, efficient for watchOS real-time updates.

Case

Case defines a value in an enum or switch statement.

enum Direction {
    case north, south
}

Usage tip: Model states in SwiftUI views for iOS navigation; compact enums suit watchOS glance interfaces.

Computed Property

A computed property calculates its value rather than storing it.

struct Circle {
    var radius: Double
    var area: Double {
        return Double.pi * radius * radius
    }
}

Usage tip: Derive UI values in SwiftUI models for iOS; recompute on watchOS for dynamic complications.

D

Dictionary

A Dictionary is an unordered collection of key-value pairs.

var scores: [String: Int] = ["Alice": 100]

Usage tip: Store app settings in iOS; on watchOS, for quick lookup in health data tracking.

Deinit

Deinit is a deinitializer called when a class instance is deallocated.

class Resource {
    deinit {
        print("Resource released")
    }
}

Usage tip: Clean up observers in iOS views; manage memory leaks on watchOS for long-running apps.

Do-Catch

Do-catch handles errors in a block of code.

do {
    try riskyOperation()
} catch {
    print(error)
}

Usage tip: Wrap network calls in SwiftUI tasks for iOS; graceful error handling on watchOS prevents crashes.

Default

Default provides a fallback in switch statements or protocol extensions.

switch value {
case 1: print("One")
default: print("Other")
}

Usage tip: Handle unexpected states in iOS UI logic; ensure coverage on watchOS for reliability.

Delegate

Delegate is a protocol-based pattern for object communication.

protocol DataDelegate {
    func didReceiveData()
}

Usage tip: Use for UIKit integration in SwiftUI on iOS; lightweight delegates for watchOS extensions.

E

Enum

Enum defines a group of related values.

enum Planet {
    case earth, mars
}

Usage tip: Type-safe options in SwiftUI pickers for iOS; enums for watchOS workout types.

Extension

Extension adds functionality to existing types.

extension String {
    var uppercase: String {
        return self.uppercased()
    }
}

Usage tip: Extend SwiftUI views for custom modifiers on iOS; reusable code for watchOS utilities.

Error

Error is a protocol for types representing errors.

enum NetworkError: Error {
    case invalidURL
}

Usage tip: Custom errors in async functions for iOS alerts; log on watchOS for debugging.

F

For-In Loop

For-in loop iterates over a sequence.

for number in 1...3 {
    print(number)
}

Usage tip: Populate SwiftUI lists on iOS; efficient iteration for watchOS sensor data.

Func

Func declares a function.

func add(a: Int, b: Int) -> Int {
    return a + b
}

Usage tip: Modular code in SwiftUI view models for iOS; pure functions for watchOS calculations.

Fallthrough

Fallthrough allows execution to continue to the next case in a switch.

switch character {
case "a":
    fallthrough
case "e":
    print("Vowel")
default: break
}

Usage tip: Group cases in iOS parsing logic; rarely used on watchOS due to simplicity needs.

Final

Final prevents overriding in subclasses.

final class Immutable {
    let value: Int
    init(value: Int) { self.value = value }
}

Usage tip: Seal classes in iOS libraries; optimize performance on watchOS by preventing inheritance.

ForEach

ForEach is a SwiftUI view that creates views from a collection.

ForEach(1..<5) { number in
    Text("\(number)")
}

Usage tip: Build dynamic lists in iOS apps; id keys ensure smooth updates on watchOS.

All letters · The full guide · Articles