Swift and SwiftUI Roadmap

Swift is the main language for building apps on iPhone, iPad, Mac, Apple Watch, Apple TV and Vision Pro, and SwiftUI is the framework most new Apple apps use for their interface. Companies that ship to Apple platforms expect both, and interviews test the language as much as the framework.

This roadmap starts with installing the tools and writing plain Swift, then covers types, protocols, generics, errors and memory. It moves on to SwiftUI views, state and navigation, then concurrency, networking, persistence, architecture, testing and packages. A final topic shows how Swift runs on the server. Each topic has a short explanation and one exercise.

By the end you will be able to build a complete app, structure it so it can be tested, and answer the language and framework questions that interviewers ask. Practise in coding practice and track progress in progress page.

Level
Beginner to advanced
Time
14-20 weeks at about 8 hours a week, less if you already know another typed language
Scope
65 topics in 10 stages
Before you start
Basic programming ideas in any language: variables, loops, functions; A Mac that can run the current version of Xcode for app work (the language itself also runs on Linux and Windows); Comfort with files, folders and the terminal; Optional: Git and GitHub Roadmap for the projects

What you will be able to do

  • Write idiomatic Swift using optionals, enums, protocols, generics and closures.
  • Explain value and reference types and manage memory with ARC.
  • Build multi-screen SwiftUI apps with navigation, lists, forms and animation.
  • Choose the right state tool for each piece of data and explain data flow.
  • Write safe concurrent code with async and await, task groups and actors.
  • Store data with files, SwiftData or a database, and call web APIs.
  • Structure an app with MVVM and dependency injection, and test it with XCTest and Swift Testing.

The roadmap at a glance

  1. Stage 1Meet Swift and Your ToolsBeginner · 1 week · 4 topics
  2. Stage 2Swift Language BasicsBeginner · 2-3 weeks · 8 topics
  3. Stage 3Control Flow, Functions and ClosuresBeginner · 2 weeks · 5 topics
  4. Stage 4Types, Protocols and MemoryIntermediate · 3 weeks · 10 topics
  5. Stage 5Errors, Memory and Language Power FeaturesIntermediate · 2 weeks · 4 topics
  6. Stage 6SwiftUI FundamentalsIntermediate · 3 weeks · 9 topics
  7. Stage 7State and Data FlowIntermediate · 2-3 weeks · 7 topics
  8. Stage 8Navigation, Animation and PolishIntermediate · 2 weeks · 4 topics
  9. Stage 9Concurrency, Networking and PersistenceAdvanced · 3 weeks · 9 topics
  10. Stage 10Architecture, Testing, Packages and the ServerAdvanced · 3 weeks · 5 topics

Stage 1 Meet Swift and Your Tools

Beginner1 week4 topics

Goal. Install the tools, run Swift code and explain where the language and SwiftUI fit.

Introduction to Swift & SwiftUI Core

Swift is a compiled, statically typed language from Apple. SwiftUI is Apple's framework for building user interfaces by describing what the screen should look like for the current data. You write the description, and the framework updates the screen when the data changes.

What is Swift? A general-purpose language that favours safety: variables must be initialised, types are checked at compile time and missing values are explicit. Where Swift is used: iPhone, iPad, Mac, Apple Watch, Apple TV and Vision Pro apps, plus command line tools and backend services.

Learn the language first and the framework second. Most SwiftUI difficulty is really a Swift gap in closures, protocols or generics.

Practice. Write down the Apple platforms you want to target and one app idea for each.

Why Use Swift? Core

Why use Swift? For Apple platforms it is the first-class choice, with the newest frameworks designed for it. It is concise, catches many mistakes before the app runs, and has fast native performance with automatic memory management that avoids a garbage collector pause.

Swift vs. Objective-C: Objective-C is the older language and many large codebases still contain it. The two interoperate, so you can call one from the other in the same app. New code and new Apple frameworks are written in Swift, and most job listings now expect it, though you may meet Objective-C when maintaining older apps.

Swift is open source and also runs on Linux and Windows, which matters later for server work.

Practice. Find one open source Swift project and read a file, noting three features you do not recognise.

Installing Swift Core

On a Mac, install Xcode from the App Store. It contains the compiler, simulators, interface previews and debugger, and it is the main tool for building apps. Check the toolchain with swift --version in a terminal.

Other editors work for the language itself. IDEs and editors with Swift support include VSCode with the Swift extension, and Emacs and Neovim through the language server that ships with the toolchain. They are good for packages and server code, but app work still depends on Xcode for signing, simulators and previews.

On Linux and Windows, install a toolchain from the official Swift download. Keep the Xcode version in mind: each release supports a range of operating system versions and language features.

Practice. Install Xcode, create a command line project and print a line, then run it from the terminal with swift.

Swift Playgrounds Recommended

Swift Playgrounds is both an Xcode feature and an app for iPad and Mac where you write Swift and see results immediately. It is a good place to try ideas without creating a full project: write a few lines, run them and inspect values.

The playground in Xcode lets you try a function or a collection method in seconds. The app version also supports building small SwiftUI apps and has lessons for beginners.

Use a playground for experiments, but move real code into a project with tests. Playgrounds are not suited to long-running work, large apps or performance measurement, and they behave differently from a full build in some details.

Practice. Open a playground and test three string methods, writing the output you expect before each run.

Stage 2 Swift Language Basics

Beginner2-3 weeks8 topics

Goal. Write small Swift programs using the core types, operators and optionals correctly.

Constants and Variables Core

Use let for values that never change and var for values that do. Prefer let: the compiler enforces it, and code is easier to read when most values are fixed.

let name = "Ada"
var score = 0
score += 10

Constants and variables must be given a value before use, and a constant can be assigned once later if the compiler can prove it. Names use camel case, and Unicode names are allowed but unwise. A constant holding a class instance still lets you change the instance's properties, because let fixes the reference, not the object. With a struct, let makes the whole value immutable.

Practice. Declare five values, decide which are let and which are var, and justify each choice.

Type Safety in Swift Core

Swift will not silently mix types. Adding an Int to a Double needs an explicit conversion, and passing the wrong type to a function is a compile error.

Type annotations state a type explicitly: var age: Int = 30. Type inference lets the compiler work it out from the value, so let city = "Oslo" is a String. Annotate when the inferred type would be wrong, for example let ratio: Double = 3, or when you declare without a value.

Type casting checks and converts class types at runtime. Use is to test, as? for a safe cast that returns an optional, and as! only when failure would be a programmer error. Prefer protocols and generics to casting.

Practice. Write a line that fails because of a type mismatch, read the error, and fix it two different ways.

Numbers and Booleans Core

Integers in Swift are Int for everyday use, matching the platform word size, with sized variants such as Int8, UInt32 and Int64 for specific needs. Use Int unless you have a reason not to. Integer overflow is a runtime error by default, and the &+ operators wrap instead.

Floats and Doubles: Double has 64-bit precision and is the default for decimals, while Float is 32-bit. Neither is exact for money, so use Decimal for currency.

Booleans are true or false of type Bool. Conditions must be real booleans: if count does not compile, if count > 0 does. A Bool has a handy toggle() method.

Practice. Compute the average of three integers as a Double and explain why dividing integers first gives a different answer.

Strings in Swift Core

Strings in Swift are value types that handle Unicode correctly. A visible character is a Character, which may be several code points, so count walks the text rather than returning a byte length, and indexes are not plain integers.

Print & string interpolation: print("Hello, \(name)") writes to the console and inserts any expression in the text. Multi-line strings use triple quotes. Useful methods include hasPrefix, contains, split and uppercased.

Comments in Swift use // for a line and /* */ for blocks, which can nest, and /// for documentation comments that tools turn into help. Semicolons in Swift are optional at the end of a line and only needed to put several statements on one line.

Practice. Reverse the words in a sentence and print the result with interpolation, handling an emoji correctly.

Operators in Swift Core

Arithmetic operators in Swift are + - * / and % for remainder. They do not overflow silently. Comparison operators are ==, !=, <, >, <= and >=, and work on any type that supports them. Logical operators are &&, || and !, and they short-circuit.

The nil-coalescing operator ?? supplies a fallback for an optional: let shown = nickname ?? "Guest". Range operators 1...5 and 0..<n make closed and half-open ranges and appear in loops and slicing. The ternary condition ? a : b picks between two values.

Swift has no ++. Use += 1. You can define your own operators, though they should be rare.

Practice. Write a function that clamps a number between two bounds using only comparison operators and the ternary.

Optionals and nil Core

An optional wraps a value that may be missing. String? is either a string or nil, and the compiler forces you to deal with both cases, which removes a large class of crashes.

var email: String? = nil
if let email { print(email.count) }          // optional binding
let size = email?.count                      // optional chaining
let safe = email ?? "none"

Optional chaining stops at the first nil and returns nil for the whole expression. guard let unwraps and exits early, keeping the rest of a function unindented. Force-unwrapping with ! crashes on nil, so use it only when nil is truly impossible.

Practice. Parse a string to an Int with Int(text), then handle the failure three ways using if let, guard let and the nil-coalescing operator.

Tuples in Swift Recommended

Tuples in Swift group a few values into one compound value without declaring a type. They suit returning several results from a function.

func range(of xs: [Int]) -> (min: Int, max: Int) {
    (xs.min() ?? 0, xs.max() ?? 0)
}
let r = range(of: [3, 9, 4])
print(r.min, r.max)

You can name the elements, read them by index, and destructure: let (lo, hi) = r. Tuples are good for small, local results. Once the grouping has meaning across your code, or more than three elements, use a struct, which can carry methods and conform to protocols.

Practice. Return a tuple of average, minimum and maximum from one function and then convert it to a struct.

Collections Core

The three main collections are Array (ordered), Set (unordered, unique) and Dictionary (key to value). All are value types and generic, and all are copied lazily, so passing them around is cheap.

var scores = ["Ada": 90, "Linus": 80]
scores["Grace"] = 95
let top = scores.values.max() ?? 0
let doubled = [1, 2, 3].map { $0 * 2 }

Dictionary lookups return an optional because the key may be absent. Learn map, filter, reduce, sorted and compactMap, which replace many loops and are common in interviews. Choose a set for fast membership tests, and avoid mutating a collection while iterating it.

Practice. Group a list of words by their first letter into a dictionary of arrays.

Stage 3 Control Flow, Functions and Closures

Beginner2 weeks5 topics

Goal. Control program flow and write functions and closures confidently.

If / Else and Switch/Case Statements Core

If / Else statements need no parentheses around the condition but require braces. They can also unwrap optionals with if let.

Switch/Case statements are far more powerful than in C-style languages. They must be exhaustive, do not fall through, and can match ranges, tuples, enum cases and conditions with where.

switch score {
case 90...100: print("A")
case 70..<90:  print("B")
default:       print("Try again")
}

Since Swift 5.9, if and switch can be used as expressions that produce a value, which keeps assignments short. Exhaustiveness is the real advantage: when you add an enum case, the compiler shows every switch that must change.

Practice. Write a switch on an enum with associated values and then add a new case to see the compiler error.

Loops Core

For-in loops in Swift iterate over ranges, arrays, dictionaries and any sequence: for item in items { ... }. Use for i in 0..<n for counted loops and enumerated() when you need the index.

While loops in Swift check the condition first. The repeat...while loop checks after the body, so it runs at least once. Continue & break in Swift loops skip to the next iteration or leave the loop, and labelled statements let you break an outer loop from an inner one.

Prefer map, filter and first(where:) when you are transforming or searching, and a loop when you have side effects or need early exit. Avoid changing a collection while looping over it.

Practice. Print a multiplication table with a nested loop, using a labelled break to stop once a product exceeds 50.

Basic Functions Core

Functions use func, a parameter list and an arrow for the return type. Swift parameters have an argument label used by callers and a parameter name used inside.

func greet(_ name: String, from city: String = "Oslo") -> String {
    "Hello \(name) from \(city)"
}
greet("Ada")
greet("Ada", from: "Rome")

Parameters in Swift functions and closures can have default values, be variadic with Int..., or be inout to change the caller's variable. Return types can be omitted for Void, and a single expression body needs no return. Functions that can fail are marked throws.

Practice. Write a function with a default argument and a variadic parameter and call it three ways.

Function Types and Nested Functions Recommended

Every function has a type made from its parameters and return value, such as (Int, Int) -> Int. Function types let you store functions in variables, pass them as arguments and return them.

func makeAdder(_ n: Int) -> (Int) -> Int {
    func add(_ x: Int) -> Int { x + n }   // nested function
    return add
}
let addFive = makeAdder(5)

Nested functions live inside another function, can see its local values and keep them alive after it returns, which is capturing. Return types that are functions are how Swift expresses factories and callbacks. This idea underlies closures and higher-order collection methods.

Practice. Write a function that returns a counter closure and explain which variable is captured.

Closures Core

A closure is an unnamed block of code that can capture values from its surroundings. Closures are everywhere in Swift: collection methods, completion handlers, animations and SwiftUI buttons.

Swift allows short forms. With trailing closures, the closure goes after the parentheses:

let sorted = names.sorted { $0 < $1 }
Button("Save") { save() }

Shorthand names $0 and $1 are fine for tiny closures. Closures that outlive the call, such as stored handlers, are @escaping. A closure that captures self strongly in a class can create a reference cycle, so capture with [weak self] when the closure is stored by that object.

Practice. Sort an array of people by age then name using a trailing closure, then rewrite it with explicit parameter names.

Stage 4 Types, Protocols and Memory

Intermediate3 weeks10 topics

Goal. Model data with value and reference types, protocols and generics, and manage errors and memory safely.

Structures & Classes Core

Structures and classes both hold properties and methods. Structs are value types: assigning or passing one copies it. Classes are reference types: variables share one instance, and classes support inheritance and deinitialisers.

Methods in Swift structures and classes are functions attached to the type. A method on a struct that changes its own properties must be marked mutating.

struct Point { var x = 0, y = 0
  mutating func move(by dx: Int) { x += dx } }

Default to structs. Swift's standard library and SwiftUI views are structs, and value semantics remove a class of shared-state bugs. Use a class when you need identity, shared mutable state, inheritance from a framework class or deinit behaviour.

Practice. Copy a struct and a class instance, change the copy, and explain the difference in the original.

Properties Core

Stored properties hold a value in each instance, either let or var, and can be lazy to compute on first use. Computed properties have no storage: they calculate a value through a getter and optional setter.

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

Property observers, willSet and didSet, run when a stored property changes, useful for validation or updating dependent state. They are not called during initialisation. Type properties, declared with static, belong to the type, not an instance.

Computed properties keep data derived and consistent instead of storing two copies that can drift apart.

Practice. Add a computed full name and a didSet observer that logs changes to a Person struct.

Property Wrappers Core

A property wrapper packages reusable storage behaviour behind an attribute. You write it once as a struct with a wrappedValue, and apply it with @Name.

@propertyWrapper
struct Clamped {
  private var value = 0
  var wrappedValue: Int {
    get { value }
    set { value = min(max(newValue, 0), 100) }
  }
}

SwiftUI relies on wrappers heavily: @State, @Binding and @AppStorage are all wrappers. Many also expose a projected value through a dollar sign, such as $name, which in SwiftUI gives a binding. Knowing how wrappers work removes the mystery from the state system covered later.

Practice. Write a wrapper that trims whitespace from a string and apply it to two properties.

Initialization Core

Initialisation sets every stored property before an instance can be used. Structs get a memberwise initialiser for free, and you can add your own in the type or in an extension to keep the free one.

Classes have designated initialisers, which fully set up the class and call the superclass, and convenience initialisers, which call another initialiser. Failable initialisers, init?, return nil when input is invalid.

Swift's two-phase rule: all properties are set first, then you may use self. Properties with default values or optionals reduce boilerplate. Prefer failable or throwing initialisers over objects in an invalid state.

Practice. Create a failable initialiser for an Email struct that rejects strings without an at sign.

Inheritance Recommended

A class can inherit from one superclass, gain its properties and methods, and override them with the override keyword. Use super to call the parent implementation, and final to prevent further subclassing or overriding.

Inheritance is less central in Swift than in many languages. Structs and enums cannot inherit, and protocols with extensions cover most reuse. Apple frameworks still use class hierarchies, so you will subclass types like UIViewController in UIKit code.

Prefer composition and protocols for your own models. Keep hierarchies shallow, mark classes final unless they are designed for subclassing, and be careful with initialisers that subclasses must implement.

Practice. Create a base class and a subclass that overrides one method and calls super.

Enumerations Core

Enumerations define a fixed set of cases and are much richer than in C. Cases can carry associated values, have raw values, include methods and computed properties, and conform to protocols.

enum Payment {
  case cash
  case card(last4: String)
  case transfer(iban: String)
}

Enums with associated values model states that exist together with their data, which makes illegal states unrepresentable. CaseIterable generates allCases, and indirect allows recursive cases. Optional itself is an enum with some and none, and Result is another.

Practice. Model a network request state as an enum with idle, loading, loaded and failed cases.

Protocols Core

A protocol declares requirements, such as properties and methods, that conforming types must provide. Structs, classes and enums can all conform. Protocols are Swift's main tool for abstraction.

protocol Shape { var area: Double { get } }
extension Shape { func describe() -> String { "Area \(area)" } }

Protocol extensions provide default implementations, which is the basis of protocol-oriented design. Common standard protocols are Equatable, Hashable, Comparable, Codable and Identifiable. Use some Shape for an opaque return type, and any Shape for a boxed existential when types vary at runtime. SwiftUI's View is a protocol.

Practice. Define a protocol with a default implementation and conform one struct and one class to it.

Extensions and Subscripts Recommended

Extensions add methods, computed properties, initialisers and protocol conformance to an existing type, even one you do not own. They cannot add stored properties. They are also how you organise a type into sections by protocol.

extension String {
  var isBlank: Bool { trimmingCharacters(in: .whitespaces).isEmpty }
}

Subscripts let a type be indexed with square brackets, like array[0] or dict["key"]. Define your own for a grid or matrix type with subscript(row: Int, column: Int) -> Int. Use extensions sensibly: too many global helpers on standard types make code hard to follow.

Practice. Add an extension on Array that safely returns an element by index or nil, using a subscript.

Generics Core

Generics let one function or type work with any type that meets stated requirements, without losing type safety.

func largest<T: Comparable>(_ items: [T]) -> T? {
  items.max()
}
struct Stack<Element> { var items: [Element] = [] }

Array, Dictionary and Optional are all generic. Constraints use protocols, and where clauses add detail. Protocols can have associated types, such as Sequence.Element, which is why you sometimes see some and any in signatures. Swift specialises generic code at compile time, so there is usually no performance penalty.

Practice. Implement a generic Stack with push and pop and a function that accepts any Comparable array.

Access Control Recommended

Access control restricts which code can see a declaration. The levels, from widest to narrowest, are open, public, internal (the default), fileprivate and private. open also allows subclassing outside the module.

Mark helper properties and functions private so the type's public surface stays small, and expose only what other modules need. Use private(set) for properties that others may read but not write.

Access control matters most when you split an app into packages, since internal types are invisible outside their module. It also documents intent: a reader sees at once which parts are safe to use.

Practice. Mark a type with private(set) state and show what the compiler rejects from outside.

Stage 5 Errors, Memory and Language Power Features

Intermediate2 weeks4 topics

Goal. Handle failure correctly, avoid leaks and understand Swift macros and result builders.

Error Handling Core

Swift models failure with errors. Any type conforming to Error, usually an enum, can be thrown. Throwing errors in Swift uses throw, and functions that can fail are marked throws.

Catching errors in Swift uses do, try and catch:

enum LoadError: Error { case missing, corrupt }
func load() throws -> Data { throw LoadError.missing }
do { let d = try load() }
catch LoadError.missing { print("not found") }
catch { print(error) }

Error propagation means a throwing function can call another with try and pass the failure up without handling it. Use try? to turn an error into nil and try! only when failure is impossible. Result stores success or failure as a value, and async functions can throw too.

Practice. Write a throwing function with a custom error enum and handle two different cases separately.

Automatic Reference Counting (ARC) Core

Automatic Reference Counting manages memory for class instances. The runtime keeps a tally of strong references to every instance and frees the instance when that tally falls to zero. Structs and enums do not use it.

A strong reference cycle occurs when two objects hold each other strongly, so neither is ever freed. Break the cycle with weak, which becomes nil when the target goes away, or unowned, which assumes the target outlives the holder.

class Screen { var onClose: (() -> Void)?
  func setup() { onClose = { [weak self] in self?.dismiss() } } }

Closures are the usual source of cycles. Use the Instruments leaks tool or the memory graph in Xcode to find them.

Practice. Create a parent and child class that leak, confirm with a deinit print, then fix with weak.

Memory Safety Recommended

Swift prevents unsafe memory access by default. Variables are always initialised before use, arrays are bounds-checked, and overlapping access to the same memory is flagged. For example, passing one variable as two inout arguments to the same call is a compile-time error, and a runtime check catches many other exclusivity violations.

Integer overflow traps instead of wrapping, and optionals prevent null dereference. The unsafe pointer types exist for interoperability with C and for performance work, and their names signal danger.

Swift 6 extends safety to concurrency, discussed later, by checking for data races at compile time. Most of this you receive without effort. Know the idea of exclusive access and why modifying a value while reading it is a bug.

Practice. Trigger an exclusivity error by passing the same variable twice as inout and read the message.

Macros and Result Builders Optional

Result builders turn a block of statements into a combined value. SwiftUI's ViewBuilder is the best known: it lets you list views one after another inside a stack, and builds them into one view. You can write your own with the @resultBuilder attribute to make domain-specific syntax for HTML or tests.

Macros are code that runs at compile time and generates more code. Freestanding macros begin with a hash, like #Predicate, and attached macros use an at sign, like @Observable and @Model. The generated code can be inspected in Xcode.

You will mostly use macros that Apple provides. Writing a macro needs a separate package and knowledge of syntax trees, which is advanced.

Practice. Expand the @Observable macro in Xcode and read the code it generates.

Stage 6 SwiftUI Fundamentals

Intermediate3 weeks9 topics

Goal. Build screens from views, modifiers, stacks, lists and forms and preview them in Xcode.

SwiftUI Core

SwiftUI is declarative: you describe the interface for the current state, and the framework works out the changes. An app starts from a type marked @main that conforms to App and returns a Scene, which contains your root view.

@main
struct NotesApp: App {
  var body: some Scene { WindowGroup { ContentView() } }
}

Xcode shows live previews next to the code, and the SwiftUI Inspector lets you select a view in the preview and edit its modifiers visually, writing the code for you. SwiftUI runs across iOS, macOS, watchOS, tvOS and visionOS, with platform-specific adaptations.

Practice. Create a new SwiftUI project, change the text in the preview and edit one modifier using the inspector.

UIKit vs. SwiftUI Recommended

UIKit is the older, imperative framework: you create view objects, configure them and update them yourself in response to events. SwiftUI describes the interface as a function of state.

SwiftUI is faster to write and gets new platform features first, but it can lack a control you need or behave differently across operating system versions. UIKit gives fine control, a long history of answers and mature behaviour, and large existing apps are built with it.

The two mix: UIHostingController embeds SwiftUI in UIKit, and UIViewRepresentable wraps a UIKit view for SwiftUI. For a new app, start with SwiftUI and reach for UIKit for gaps. Interviewers often ask when you would pick each.

Practice. Wrap a UIKit activity indicator or text view in a UIViewRepresentable and show it in SwiftUI.

Views Core

In SwiftUI everything on screen is a view: a struct that conforms to View and has a body property returning other views. Views are cheap descriptions, not long-lived objects, and SwiftUI recreates them whenever state changes.

struct Greeting: View {
  let name: String
  var body: some View { Text("Hello, \(name)") }
}

Split screens into small views with clear inputs. This helps readability, previews and performance, because SwiftUI only recomputes views whose inputs changed. Keep body free of side effects and slow work. Views are values, so they should not hold references that need identity.

Practice. Break a long screen into three small views that each take their data as plain parameters.

Text and Image Core

Text shows a string and supports styling, truncation, line limits and localised keys. The font modifier sets the size and weight: Text("Title").font(.title.bold()). Prefer system text styles such as .headline and .body because they scale with Dynamic Type for accessibility.

Image displays pictures from the asset catalogue, from SF Symbols with Image(systemName: "star"), or from data. Mark images resizable() before sizing them, and use scaledToFit() or scaledToFill(). For remote images, AsyncImage loads a URL and offers a placeholder.

Attach an accessibility label to meaningful images, and hide decorative ones from assistive technology.

Practice. Build a profile header with a system symbol, a title in a text style and a caption.

Button and UI Controls Core

Button takes an action closure and a label. It is the base for most interaction.

Button("Add") { count += 1 }
Button(role: .destructive) { delete() } label: { Label("Delete", systemImage: "trash") }

Other UI controls include Toggle, Slider, Stepper, Picker, DatePicker, TextField and SecureField, most of which take a binding to the value they edit. Use the .disabled(_:) modifier to turn off a control, and the buttonStyle modifier to change appearance.

Choose the control that matches the data: a Picker for a fixed set, a Stepper for small counts. Standard controls bring accessibility and platform behaviour for free.

Practice. Build a settings panel with a toggle, a slider and a picker, each bound to its own state value.

View Modifiers Core

A modifier wraps a view and returns a new one. They chain, and order matters because each wraps the result of the previous.

Text("Hi")
  .padding()
  .background(Color.blue)
  .clipShape(RoundedRectangle(cornerRadius: 12))

Here padding comes before the background, so the background includes the padding. Reverse them and the colour hugs the text only. Padding adds space, the background view modifier sets what sits behind, and clipShape cuts a view to a shape. Others are frame, foregroundStyle, overlay and shadow. Extract repeated combinations into a custom ViewModifier or a View extension.

Practice. Create a card style as a custom ViewModifier and use it on three different views.

Stacks Core

Stacks are the base of layout. VStack arranges children vertically, HStack horizontally and ZStack layers them front to back.

VStack(alignment: .leading, spacing: 8) {
  Text("Title").font(.headline)
  HStack { Image(systemName: "clock"); Text("5 min") }
}

Layout works by negotiation: the parent proposes a size, the child picks its own, and the parent places it. Spacer expands to fill room, and frame(maxWidth: .infinity) makes a view take the width. Alignment guides handle finer cases. Use LazyVStack inside a scroll view for long content, since the plain version creates all children at once.

Practice. Reproduce a message row with an avatar, name, time and preview text using only stacks and spacers.

List, Grid and Form Core

List shows rows with built-in scrolling, swipe actions, selection and editing, and takes a collection of Identifiable data.

List(items) { item in Text(item.title) }

Grid lays out rows and columns with aligned cells, and LazyVGrid with GridItem columns shows large galleries lazily. Form is a grouped, platform-styled container for settings and data entry, and it works naturally with controls. TabView switches between top-level sections using a tab bar.

Give each item a stable ID. Using an array index as an ID breaks animations and state when the list changes order. Prefer ForEach inside a List for sections.

Practice. Build a tabbed app with one list tab and one form tab that adds items to that list.

GeometryReader and ViewBuilder Recommended

GeometryReader gives you the size and position of the space the parent offers, so you can size children as a proportion of it.

GeometryReader { proxy in
  Rectangle().frame(width: proxy.size.width * 0.5)
}

It expands to fill the available space, which surprises many people, so use it sparingly. Often frame, layoutPriority or the Layout protocol is cleaner.

ViewBuilder is the result builder that makes view code read as a list. You can mark your own function or a closure parameter with @ViewBuilder to accept several views and conditions, which is how containers like VStack and Group are written.

Practice. Write a reusable Card container that accepts content through a ViewBuilder closure.

Stage 7 State and Data Flow

Intermediate2-3 weeks7 topics

Goal. Choose the right state tool for each piece of data and keep views in sync.

@State Core

@State holds simple value state owned by a view. SwiftUI stores it outside the struct so it survives the struct being recreated, and updates the view when it changes.

struct Counter: View {
  @State private var count = 0
  var body: some View { Button("\(count)") { count += 1 } }
}

Mark state private because the view owns it. Use it for local, transient data such as a toggle, text in a field or whether a sheet is open. Changing state inside body is an error. State is a source of truth, so never copy it into another state value that can drift.

Practice. Build a counter with undo using two state values and explain who owns each.

@Binding Core

@Binding gives a child view read and write access to a value owned elsewhere, without copying it. The parent passes it using a dollar sign.

struct Toggler: View {
  @Binding var isOn: Bool
  var body: some View { Toggle("Enabled", isOn: $isOn) }
}
// parent: Toggler(isOn: $enabled)

The $enabled expression is the projected value of @State. Use bindings for reusable controls that edit data they do not own. Constant bindings, .constant(true), are handy in previews. Do not pass bindings deep through many layers when an observable model or the environment would be simpler.

Practice. Extract a text field with validation into a child view that edits a parent binding.

@StateObject and @ObservedObject Recommended

For reference-type models conforming to ObservableObject, mark published properties with @Published. @StateObject creates and owns the object for the life of the view. @ObservedObject watches an object created and owned somewhere else.

The rule: use @StateObject where the object is created, and @ObservedObject in children that receive it. Using @ObservedObject for creation can reset the model whenever the parent redraws.

Newer code uses the Observation framework: a class marked with the @Observable macro, held in @State by its owner. It tracks which properties each view reads, so views update more precisely. Know both, since existing code and interviews still use ObservableObject.

Practice. Create a model with an array and add method, show it in two views and then migrate it to @Observable.

@EnvironmentObject Recommended

@EnvironmentObject reads a shared object from the view hierarchy without passing it through every initialiser. An ancestor injects it with .environmentObject(model), and any descendant can read it.

It suits app-wide things such as the signed-in user or settings. The danger is that a missing injection crashes at runtime, which previews expose, so supply it in every preview.

With Observation, the equivalent is @Environment(Type.self) with .environment(model). The environment also holds system values such as colour scheme, locale and dismiss action, read with @Environment(\.colorScheme). Use the environment for dependencies that many views share and explicit parameters for everything else.

Practice. Inject a shared settings model at the app root and read it in a deeply nested view.

Data Flow Core

Data flow is the rule that each piece of data has one owner, and everything else reads or edits it through bindings, parameters or the environment. SwiftUI then redraws what depends on it.

A quick guide:

  • Plain let property when the child only reads a value.
  • @State for local value state.
  • @Binding for a child that edits a parent value.
  • @State with an @Observable class, or @StateObject, for models you create.
  • Environment for shared dependencies.

Data should flow down and events up. When two views need the same value, move it to their closest common parent. Duplicated state is the most common source of bugs.

Practice. Draw the data flow for a todo app and label which view owns each piece of state.

App Lifecycle Recommended

In SwiftUI the App protocol replaces the app delegate for most work. A Scene such as WindowGroup manages windows, and the scenePhase environment value reports active, inactive or background, so you can save data or pause work.

@Environment(\.scenePhase) private var phase
.onChange(of: phase) { if phase == .background { save() } }

Views have their own lifecycle: onAppear and onDisappear mark visibility, and .task runs async work tied to the view's life and cancels it automatically. For needs the app protocol does not cover, such as push notification registration, use UIApplicationDelegateAdaptor.

Practice. Save unsent form text when the app moves to the background and restore it on launch.

User Interaction Core

Beyond buttons, SwiftUI offers gestures such as taps, long presses, drags, magnification and rotation. Attach them with modifiers: .onTapGesture { } or .gesture(DragGesture()). Gestures can be combined with simultaneously, sequenced or exclusively, and @GestureState keeps temporary values that reset when the gesture ends.

Drag & drop moves content between views or apps. Mark a source with .draggable(item) and a target with .dropDestination(for:). Items usually conform to Transferable.

Also handle keyboard focus with @FocusState, hover on iPad and Mac, and context menus. Make sure every gesture-only action has an accessible alternative.

Practice. Build a card that can be dragged and dropped between two lists.

Stage 8 Navigation, Animation and Polish

Intermediate2 weeks4 topics

Goal. Move between screens, animate changes and make the app usable by everyone.

NavigationStack Core

NavigationStack replaces the older navigation view. It shows a root view and pushes destinations on top. NavigationLink pushes a destination when tapped, and navigationDestination(for:) maps a data type to a view so links can carry values.

NavigationStack(path: $path) {
  List(items) { i in NavigationLink(i.title, value: i) }
    .navigationDestination(for: Item.self) { DetailView(item: $0) }
}

NavigationPath stores the stack as data, so you can push, pop to root and restore state programmatically, which is the basis of deep links. For sidebar layouts on iPad and Mac use NavigationSplitView. Present modally with sheet and fullScreenCover, and keep a single source of truth for navigation state.

Practice. Build a list and detail flow driven by a NavigationPath and add a button that pops to the root.

Animations Core

Implicit animations attach to a view with .animation(_:value:) and animate whenever that value changes. Explicit animations wrap a state change: withAnimation(.spring) { isOpen.toggle() }, animating everything that depends on it.

Transitions control how a view enters and leaves the hierarchy, using .transition(.slide) or .opacity and .move(edge:), and need an animation around the change.

The Animatable protocol lets a custom value animate by exposing animatableData, which SwiftUI interpolates every frame. Shapes and custom effects use it. matchedGeometryEffect links two views for hero movement.

Use motion to explain change, keep it short, and respect the reduce motion setting.

Practice. Animate a card that expands on tap using withAnimation and a transition, and test with reduce motion enabled.

Swift Charts Optional

Swift Charts draws data with a declarative Chart view, using marks such as BarMark, LineMark, PointMark and AreaMark that you bind to data properties.

Chart(sales) { s in
  BarMark(x: .value("Month", s.month), y: .value("Total", s.total))
}

Axes, legends and scales are generated, and you can customise them. Charts follow Dynamic Type and support accessibility through audio graphs. Use them for summaries and trends inside an app, and keep a table or text alternative for exact values.

Practice. Chart seven days of sample data as bars and add a line mark for the average.

Accessibility and Localization Core

Accessibility is part of the interface. SwiftUI supports VoiceOver through labels and traits: .accessibilityLabel("Close"), .accessibilityHint and .accessibilityAddTraits. Support Dynamic Type by using text styles, test large sizes, and make touch targets at least 44 points. Do not convey meaning with colour alone, and use the Accessibility Inspector in Xcode to audit.

Localization prepares the app for other languages. Strings in Text are localised keys by default, collected in a string catalogue. Use formatting APIs for dates, numbers and plurals instead of building strings by hand, and test right-to-left layouts with the layout direction environment value.

Practice. Run the Accessibility Inspector on one screen, fix three findings and add a second language to a string catalogue.

Stage 9 Concurrency, Networking and Persistence

Advanced3 weeks9 topics

Goal. Write safe concurrent code, call APIs and store data on the device and in the cloud.

Asynchronous Functions Core

Asynchronous functions are marked async and called with await, which marks a point where the function may suspend and let other work run on the thread. Code reads top to bottom, with no callback nesting.

func loadUser(id: Int) async throws -> User {
  let (data, _) = try await URLSession.shared.data(from: url(for: id))
  return try JSONDecoder().decode(User.self, from: data)
}

An async function can only be called from an async context, such as another async function or a Task. Suspension is not blocking: the thread is free for other work. After an await, you may be on a different thread, which is why actor isolation matters. async let starts several child operations in parallel.

Asynchronous sequences deliver values over time, and you consume one with for await. Examples include lines from a URL, notifications and values from AsyncStream.

for try await line in url.lines {
  print(line)
}

AsyncStream bridges callback-based code: you create it with a continuation and yield values as events arrive. Cancelling the consuming task stops the loop. Many operations from map and filter are available as well.

Use async sequences for streams such as progress, sensor data and live updates, and plain async functions for a single result.

Practice. Fetch two resources in parallel with async let and combine the results. Then wrap a repeating timer or notification in an AsyncStream and consume it with for await.

Tasks and Task Groups Core

A Task starts asynchronous work. Tasks and task groups are the structured way to run work in parallel. withTaskGroup runs a variable number of child tasks and collects results, and all children finish before the group returns, so errors and cancellation are handled together.

let sizes = await withTaskGroup(of: Int.self) { group in
  for url in urls { group.addTask { await size(of: url) } }
  return await group.reduce(0, +)
}

Cancellation is cooperative: check Task.isCancelled or call try Task.checkCancellation() in long loops. Child tasks inherit priority and cancellation from their parent.

Unstructured concurrency creates tasks that are not tied to the scope that made them. Task { } inherits the current actor and priority, while Task.detached { } inherits neither and should be rare.

You are responsible for keeping the handle and cancelling it. A typical use is starting async work from a synchronous place, such as a button action. In SwiftUI prefer the .task modifier, which cancels with the view.

Avoid fire-and-forget tasks that touch shared state, since errors vanish. Structured concurrency, with async let and task groups, is easier to reason about and should be the first choice.

Practice. Download ten files with a task group limited to three at a time and support cancellation. Then start a Task from a button, store its handle and cancel it when the user taps again.

Actors Core

An actor is a reference type that protects its mutable state: only one task at a time runs code on it, and outside code accesses it with await. This prevents data races without manual locks.

actor Counter {
  private var value = 0
  func increment() -> Int { value += 1; return value }
}
let n = await counter.increment()

@MainActor is a global actor for the main thread, and SwiftUI views and UI code must run on it. Mark a view model @MainActor so its state updates safely. Actors are re-entrant: state can change across an await inside an actor method, so re-check assumptions after suspension.

Practice. Implement a thread-safe cache as an actor and call it from many tasks.

Strict Concurrency Checking Recommended

Swift 6 language mode turns data race checks into compile errors. The compiler verifies that values crossing between isolation domains are Sendable, meaning safe to share.

Value types made of sendable parts are sendable automatically. Classes need to be final and immutable, or be actors, or use explicit locking marked with @unchecked Sendable, which is a promise you must keep.

Migrate gradually: raise the strict concurrency setting per target, fix warnings, then switch the language mode. Annotate UI types with @MainActor, make models sendable and avoid shared global mutable state. Expect to learn the rules through compiler messages, and read them carefully.

Practice. Enable strict concurrency on one target and fix every warning in a single file.

SwiftUI with Async/Await Core

Run async work from a view with the .task modifier: it starts when the view appears and is cancelled when it disappears. Use .task(id:) to restart when an input changes, which suits search.

.task(id: query) {
  results = (try? await api.search(query)) ?? []
}

Keep the loading logic in a @MainActor model that exposes state such as idle, loading, loaded and failed, and let the view switch on it. Use .refreshable for pull to refresh. Always handle errors and loading states, and guard against out-of-order responses when the input changes quickly.

Practice. Build a search screen that debounces input, cancels stale requests and shows loading and error states.

Networking Libraries Recommended

URLSession with async methods and Codable handles most apps and needs no dependency. Wrap it behind a protocol so tests can substitute a fake.

Third-party networking libraries reduce boilerplate. Alamofire offers request chaining, retries, validation and upload progress. Moya adds a typed layer of endpoints on top of a networking library, so every API route is an enum case. They suit large API surfaces with many endpoints.

Choose based on need: plain URLSession for small apps, a library when its features save real code. Always set timeouts, decode errors cleanly, handle offline cases and never store secrets in the app bundle. See API Design Roadmap for how APIs should behave.

Practice. Write a small API client over URLSession behind a protocol, then replace the real client with a fake in a preview.

Data Persistence Core

Data persistence stores information between launches. Pick the lightest tool that fits.

  • UserDefaults & AppStorage: small preferences and flags. @AppStorage("theme") binds a value to a defaults key and updates views.
  • FileManager: reading and writing files in the app's documents or caches folder, often with Codable JSON.
  • Keychain: passwords and tokens, never defaults.
  • A database for structured, queryable data.

Never keep large data or secrets in defaults. Decide what must survive, what can be rebuilt and what should sync. Handle failures to write, and plan for schema changes when the format of saved data changes between app versions.

Practice. Persist a list of notes as JSON using FileManager and a theme choice with AppStorage.

Core Data and SwiftData Core

Core Data is Apple's long-standing object graph and persistence framework, with a model editor, contexts, fetch requests and migrations. It is mature and still widespread in existing apps.

SwiftData is the modern layer built for Swift: mark a class with @Model, query with @Query in a view, and insert through a ModelContext from the environment.

@Model class Note { var title: String; var created = Date.now
  init(title: String) { self.title = title } }

It stores data with Core Data's engine underneath and works with CloudKit for sync. Know the differences, since interviews still ask about Core Data concepts such as contexts, and plan migrations whenever the model changes.

Practice. Create a SwiftData model, list it with @Query and add delete and edit actions.

Databases, CloudKit and Firebase Optional

Other options exist beyond Apple's frameworks. Databases such as SQLite, accessed with GRDB, give full SQL control, and Realm offers an object database with live results. Choose them for complex queries or data shared with non-Apple platforms.

CloudKit syncs data through the user's iCloud account, and suits Apple-only apps that want sync without running a server. Firebase, from Google, provides authentication, cloud databases, storage and analytics for cross-platform apps, at the price of a third-party dependency and its usage terms.

Whichever you choose, think about conflict resolution, offline behaviour, privacy rules and what happens when a user signs out. See SQL Roadmap for query basics.

Practice. List what would break if two devices edited the same note offline, and how you would resolve it.

Stage 10 Architecture, Testing, Packages and the Server

Advanced3 weeks5 topics

Goal. Structure an app for change, test it, share code in packages and run Swift on the server.

App Architecture Core

App architecture is how you divide responsibilities. SwiftUI leads naturally to MVVM: the model holds data and rules, the view model prepares state for a view, and the view renders it. With Observation, a view model is a @MainActor @Observable class owned by the view.

Clean Architecture separates layers so business rules do not depend on frameworks: entities, use cases, and gateways that the outer layers implement. It pays off in large apps and is overkill in small ones.

Dependency Injection passes collaborators in through initialisers, or through the environment, instead of creating them inside. It makes code testable, because a test supplies a fake. Keep views thin, avoid singletons that hide dependencies, and add layers only when a real problem demands them.

Practice. Refactor a view that fetches its own data into a view model with a protocol-based service.

Testing Core

Testing in Swift has two frameworks. XCTest is the original: subclass XCTestCase, write methods beginning with test, and use XCTAssertEqual and friends. It also runs UI tests and performance tests.

Swift Testing is the newer framework built on macros: mark a function with @Test, check with #expect, group with suites, and parameterise one test over many inputs.

@Test(arguments: [1, 2, 3])
func doubling(_ n: Int) { #expect(n * 2 == n + n) }

Test models and view models heavily, since they need no screen. Use protocols and fakes for networking and storage, and keep a handful of UI tests for critical flows. Async tests simply use async functions.

Practice. Write a Swift Testing suite for a view model with a fake service, covering success and failure.

Logging and Debugging Core

Logging and debugging start with print, but real apps need more. The unified Logger from os records levels, categories and privacy for values, and shows up in Console. For packages and server code, the Swift-Log API defines a common logging front end that backends plug into. Third-party loggers such as CocoaLumberjack add file output and rotation.

The Xcode debugger offers breakpoints with conditions and actions, the variables view, po in the console and the view hierarchy debugger. Use Instruments for time profiling, memory and leaks, and the memory graph for retain cycles.

Log at appropriate levels, never log secrets or personal data, and reproduce bugs with a failing test before fixing.

Practice. Add a Logger with categories to a network client and find one slow call using Instruments.

Swift Package Manager Core

Swift Package Manager builds and distributes code. A package is described by a Package.swift manifest listing targets, products and dependencies.

Using packages in an app: add a dependency by its repository address and version rule in Xcode or in the manifest, then import the module. Creating Swift packages is simple: swift package init produces a library or executable with a test target. Splitting an app into local packages gives clean boundaries, faster builds and access control that matters.

Swift Package Manager plugins run tools at build time, such as code generators or linters. The Swift Package Index is a community site to discover packages and check platform compatibility. DocC builds documentation from /// comments and articles, and can host a catalogue for your package.

Practice. Extract a model layer into a local package with tests and add a documentation comment that builds in DocC.

Swift for Server Apps Optional

Swift for server apps uses the same language on Linux. Server frameworks include Vapor, a full-featured web framework with routing, Fluent for databases and authentication, and Hummingbird, a lighter, modular option. Both sit on SwiftNIO, the event-driven networking library that provides asynchronous I/O. MongoKitten is a native MongoDB driver.

Sharing model code between an iOS app and a backend avoids duplicated types. Deployment uses containers, and the Static Linux SDK builds statically linked executables that are easy to ship.

Swift also compiles to WebAssembly, and SDKs for WebAssembly (Wasm) are available for experimentation in browsers and edge runtimes. These areas are newer, so check what is current before committing.

Practice. Create a small Vapor or Hummingbird service with one JSON route and test it with curl.

Projects to build

Build these in order. Each one should end up in a public repository with a short README that explains your decisions.

  1. Tip and split calculatorBeginner

    Build a one-screen calculator with a text field for the bill, a slider or picker for the tip and a stepper for the number of people. Show the total per person and format values as currency.

    State · Controls · Stacks · Number formatting

  2. Notes app with persistenceIntermediate

    Build a notes list with add, edit, delete and search. Store notes with SwiftData and save the chosen sort order with AppStorage. Add navigation to a detail screen.

    NavigationStack · SwiftData · List · Binding

  3. Weather or news readerIntermediate

    Fetch data from a public API with async and await, decode it with Codable and show loading, error and empty states. Cache the last result on disk so the app opens with content offline.

    URLSession · Codable · Async tasks · Error handling

  4. Habit tracker with chartsAdvanced

    Track daily habits with streaks, a weekly chart using Swift Charts, local notifications and accessibility labels. Structure the app with view models and test the streak logic.

    MVVM · Swift Charts · Testing · Accessibility

  5. Shared package and serverAdvanced

    Put your models and networking in a local Swift package. Build a small Vapor or Hummingbird backend that uses the same models, and connect the app to it with authentication.

    Swift packages · Server Swift · Dependency injection · Concurrency

Interview questions

Try to answer each question out loud before you open the answer.

What is the difference between a struct and a class in Swift?Junior

Structs are value types and are copied on assignment. Classes are reference types, so variables share one instance. Classes support inheritance and deinitialisers, and are managed by reference counting. Structs get a memberwise initialiser and need mutating for methods that change them. Swift favours structs for models, and SwiftUI views are structs. Use a class when you need shared identity or inheritance.

What are optionals and how do you unwrap them safely?Junior

An optional is a type that holds either a value or nil, written with a question mark. The compiler forces you to handle both cases. Safe options are optional binding with if let or guard let, optional chaining with ?., and the nil-coalescing operator ??. Force unwrapping with an exclamation mark crashes on nil, so I use it only when nil is a programmer error.

Explain how ARC works and how a retain cycle happens.Mid

Automatic Reference Counting counts the strong references held to each class instance and frees the instance when the count reaches zero. A retain cycle occurs when two instances hold strong references to each other, or an object stores a closure that captures it strongly, so the count never reaches zero. Break it with weak or unowned, usually via a capture list like [weak self]. I find them with the memory graph.

What is the difference between let and var, and why prefer let?Junior

let declares a constant that cannot be reassigned, var a variable that can. I prefer let because it states intent, lets the compiler optimise, and avoids accidental changes. With a struct, let makes the whole value immutable. With a class, let fixes the reference but the object's own properties can still change if they are var.

What is protocol-oriented programming?Mid

It is designing with protocols and extensions instead of class hierarchies. A protocol declares requirements, an extension supplies default behaviour, and any struct, enum or class can conform. This gives reuse without inheritance and works with value types. Generics constrained by protocols keep code type-safe and fast. Class inheritance is still used where frameworks need it.

How do @State, @Binding and @Observable differ?Mid

@State stores value state owned by the view. @Binding is a reference to state owned by another view, giving read and write access. @Observable marks a class whose properties SwiftUI tracks, so views that read them update when they change. The owner holds the model in @State, and children receive it as a parameter or through the environment.

How does SwiftUI decide when to redraw a view?Senior

Views are value descriptions. When a state source that a view reads changes, SwiftUI re-evaluates that view's body, compares the result with the previous one and updates only what differs on screen. Identity, from explicit IDs or position, lets it match old and new views. So keep inputs small, avoid heavy work in body and give list items stable IDs.

What are the differences between @StateObject and @ObservedObject?Mid

@StateObject creates and owns an observable object, keeping it alive across redraws of the view. @ObservedObject only observes an object that something else owns. Using ObservedObject for creation can reinitialise the object whenever the parent redraws, losing data. With the Observation framework, you hold an @Observable model in @State instead.

Explain async and await and how they differ from completion handlers.Mid

An async function can suspend at an await without blocking its thread, then resume later. Code reads in order, errors use normal try and catch, and cancellation is built in through tasks. Completion handlers nest, make error handling and cancellation manual, and are easy to call twice or never. I wrap old callback APIs with continuations.

What is an actor and why use @MainActor?Senior

An actor is a reference type that serialises access to its mutable state, so only one task runs on it at a time, preventing data races. Outside callers use await. @MainActor is a global actor tied to the main thread. UI code must run there, so I mark view models and UI types with it so their state changes happen safely.

How do you choose between Core Data, SwiftData and a plain file?Mid

For small preferences use AppStorage. For modest data that is read and written whole, a Codable JSON file is simple. For structured, queryable data with relationships, use SwiftData in new apps with modern minimum versions, or Core Data when supporting older systems or existing stores. For heavy SQL needs, use SQLite through a library like GRDB.

How would you structure and test a SwiftUI app?Senior

I use MVVM: views render state, @MainActor view models hold logic, and services sit behind protocols. Dependencies are injected through initialisers, so tests pass fakes. I unit test view models and services with Swift Testing or XCTest, and keep a few UI tests for sign-in and checkout style flows. Previews use sample data.

What does the some keyword mean, for example some View?Mid

some View is an opaque return type: the function returns one specific type that conforms to View, but callers only see the protocol. The compiler still knows the exact type, so there is no runtime boxing cost. It differs from any View, which is an existential that can hold different types at runtime and has a cost.

When would you use UIKit instead of SwiftUI?Mid

When SwiftUI lacks a control or behaves differently on older operating systems, when an existing app is built in UIKit, or when I need fine control over layout, text or collection performance. I can embed UIKit in SwiftUI with representable types and the reverse with hosting controllers, so most apps mix them.

What is the difference between escaping and non-escaping closures?Mid

A non-escaping closure is only called during the function call and then discarded, which is the default. An escaping closure is stored or called later, such as a completion handler, and must be marked @escaping. Escaping closures that capture a class instance can create retain cycles, so I capture weakly where appropriate.

Common mistakes

  • Force unwrapping optionals with an exclamation mark everywhere; use if let, guard let or a default instead.
  • Making everything a class; start with structs and use classes only for shared identity.
  • Creating a model with @ObservedObject inside a view, which resets it on redraw; use @StateObject or @State.
  • Doing network calls or heavy work inside body; move them to .task or a model.
  • Capturing self strongly in stored closures; use a capture list to avoid leaks.
  • Using array indices as list IDs; use stable identifiers so animations and state stay correct.
  • Updating UI state from a background context; mark UI models with @MainActor.
  • Putting all logic in views; extract view models and services so it can be tested.
  • Ignoring Dynamic Type and VoiceOver until late; build with text styles and labels from the start.

Ready-for-interview checklist

  • I can explain value versus reference types and choose between struct and class.
  • I can use optionals safely with binding, chaining and nil-coalescing.
  • I can write closures, including trailing closures and capture lists.
  • I can define protocols with extensions and use generics with constraints.
  • I can throw, catch and propagate errors and design an error enum.
  • I can explain ARC and fix a retain cycle.
  • I can build screens with stacks, lists, forms and modifiers and explain modifier order.
  • I can pick the right state tool and explain data flow.
  • I can navigate with NavigationStack and a path.
  • I can write async code with tasks, task groups and actors.
  • I can persist data with files, AppStorage or SwiftData.
  • I can structure an app with MVVM and dependency injection and test it.
  • I can create and consume a Swift package.

Related roadmaps

FAQ

Should I learn Swift or SwiftUI first?

Learn enough Swift first: types, optionals, closures, structs and protocols. SwiftUI code relies on all of them. Then learn SwiftUI while continuing to deepen the language. Doing both together from day one slows beginners down.

Do I need a Mac to learn Swift?

For app development, yes, because Xcode runs only on macOS. You can learn the language on Linux or Windows with the official toolchain, and practise with server and command line projects.

Is UIKit still worth learning?

Yes, a little. Many existing apps use it and interviews ask about it. Learn the basics of view controllers and the lifecycle, and how to embed UIKit and SwiftUI in each other, but start new work with SwiftUI.

How long does it take to get job-ready?

With steady practice, about four to five months to build and test a real app. Concurrency, architecture and testing take the longest, and building two or three complete apps matters more than finishing every topic.

Is Swift only for Apple devices?

No. Swift runs on Linux and Windows, powers server frameworks, and can compile to WebAssembly. Apple apps are still the main use and where the jobs are.

Practise while you learn.Solve interview problems in the browser, with hints and a timer.
CodingSQLSystem design
Next Post Previous Post
No Comment
Add Comment
comment url