© Interview RuntimeThis content is copyright. Copying is disabled; you may quote a short excerpt with a link to the page.

iOS coding interview, 3 Swift tasks to practise under time pressure

3 timed Swift exercises for practising under pressure, covering a latest-intent search model, a shared image request and a bounded cache.

Engraving of a stopwatch lying open beside a set of fine screwdrivers.

In short

  • Pick 1 task, hide its reference code and set the timer before you write anything.
  • Debounce controls when work starts, while a revision check controls whether its result may publish.
  • Shared work needs an ownership policy that stays separate from each waiter's cancellation.
  • A bounded cache must update recency on reads, not only on inserts.
  • Repeat each task with its follow-up, changing 1 constraint, and keep both attempts.

Your search works until responses arrive backwards. Your image loader works until 2 rows request the same image. Your cache works until reading an entry is supposed to keep it alive.

Each implementation can look convincing in a quick demo. A small change in the execution order reveals whether its contract is clear.

These 3 Swift tasks give you practical iOS coding interview practice without requiring a complete app. Each has a candidate brief, a timebox, reference code, a failure case and a follow-up. They are original exercises chosen for their teaching value, not claims about how frequently employers ask them.

Ask your recruiter whether the real round uses algorithms, app coding or both. For how the live round is scored, see the scoring notes for the live iOS coding round. These tasks train application-oriented reasoning. They do not replace algorithm preparation where it is required.

How to run the practice

Pick 1 task per session. Hide its reference implementation, set the timer and explain the behaviour you intend to preserve before writing code.

Use a working Swift environment. The examples use Foundation and Swift concurrency; no SwiftUI project is required. The reference implementations were checked with Apple Swift 6.3.2 in Swift 6 language mode.

TaskSuggested timeboxMain question
Debounced search30 minutesWhich operation may publish state?
Shared image requests30 minutesWho owns work needed by several callers?
Bounded LRU cache25 minutesWhich operations change recency?

The first attempt should produce the smallest correct behaviour you can verify. Use the follow-up in a second attempt if it would otherwise crowd out the baseline.

Task 1, debounced search with latest-intent state

Candidate brief

Implement the model for product search. Wait 300 milliseconds before calling the service. A new query replaces the previous intent. An empty query clears the screen. An obsolete result or error must not change the current screen.

Clarify that previous results are cleared when a new query starts. Cancellation is not a visible error. For this exercise, an external caller owns the task and should cancel its previous task when the input changes. A SwiftUI integration can provide such ownership, but that integration is outside this model.

The debounce waits before starting work. The revision check protects publication after work finishes. They address separate parts of the behaviour.

A compact reference implementation

import Foundation

@MainActor
final class SearchModel {
    typealias Search = @Sendable (String) async throws -> [String]

    private let fetch: Search
    private let debounce: Duration
    private var revision = UUID()

    private(set) var results: [String] = []
    private(set) var isLoading = false
    private(set) var errorMessage: String?

    init(debounce: Duration = .milliseconds(300),
         fetch: @escaping Search) {
        self.debounce = debounce
        self.fetch = fetch
    }

    func search(_ rawQuery: String) async {
        let mine = UUID()
        revision = mine
        let query = rawQuery.trimmingCharacters(in: .whitespacesAndNewlines)
        results = []
        errorMessage = nil
        isLoading = !query.isEmpty
        guard !query.isEmpty else { return }

        defer {
            if revision == mine { isLoading = false }
        }

        do {
            try await Task.sleep(for: debounce)
            try Task.checkCancellation()
            guard revision == mine else { return }
            let found = try await fetch(query)
            try Task.checkCancellation()
            guard revision == mine else { return }
            results = found
        } catch {
            guard revision == mine, !Task.isCancelled,
                  !(error is CancellationError) else { return }
            errorMessage = "Search failed. Try again."
        }
    }
}

The main actor owns the mutable screen state. A unique revision identifies each new intent, including an empty query. After suspension, the operation checks whether its result is still relevant. Actor isolation alone does not preserve an assumption across an asynchronous call, because each await is a possible suspension point where other code runs.[1] The Task.checkCancellation() calls stop the work when the caller cancels it.[2]

The model intentionally does not start or retain its own unstructured task. Its caller owns cancellation. If the caller fails to cancel obsolete calls, revision checks still prevent obsolete publication, but an old request already inside the service may continue consuming resources.

This class also omits observation annotations and actual network transport so the behaviour can be tested independently. Add the observation mechanism appropriate to the host app when integrating it.

Verify the inconvenient order

Use a fake service with manually completed requests. Set debounce to 0 for response-order tests; check debounce behaviour separately.

Start A, start B, complete B and then complete A. Assert that B's results remain. Repeat with A failing after B succeeds. Finally, clear the query before A completes and assert that the screen stays empty.

Avoid using a real network delay to establish ordering. The test should explicitly know when each request has started and when it completes.

Follow-up, the same query appears twice

The user types cat, then dog, then cat again. Why is comparing only the response's query text insufficient?

The first and third operations have equal text but different identities. A response for the first cat may be obsolete relative to the third intent. Decide whether the product permits reuse of such a response; this implementation deliberately requires operation identity to match.

When narrating the solution, explain that policy. It makes the choice of a revision token meaningful.

If you want to repeat this exercise with a guided loop and a changed constraint, iOS Interview Training includes Guided Practice, with realistic prompts, weaknesses to inspect, revised answers and changed constraints.

Task 2, share an in-flight image request

Candidate brief

Several rows request the same image URL. Share the request while it is in flight. Remove completed or failed work so a later call can fetch again. A row disappearing must not cancel work that other rows still need.

This task loads Data, not a decoded image. Image decoding, resizing and UI presentation are separate responsibilities. Assume a URL fully identifies a request within 1 loader instance. Authentication and image transformations would require a richer key.

Choose the cancellation policy before coding. Here, the loader owns shared work until it completes. A cancelled waiter does not cancel the shared task, and waiting is not designed to return promptly on that waiter's cancellation. The UI must check relevance before publishing the eventual result.

Reference implementation

import Foundation

actor SharedDataLoader {
    typealias Fetch = @Sendable (URL) async throws -> Data

    private struct Flight {
        let id: UUID
        let task: Task<Data, Error>
    }

    private let fetch: Fetch
    private var flights: [URL: Flight] = [:]

    init(fetch: @escaping Fetch) {
        self.fetch = fetch
    }

    func data(for url: URL) async throws -> Data {
        let flight: Flight
        if let existing = flights[url] {
            flight = existing
        } else {
            let fetch = self.fetch
            let created = Flight(
                id: UUID(),
                task: Task { try await fetch(url) }
            )
            flights[url] = created
            flight = created
        }

        do {
            let data = try await flight.task.value
            if flights[url]?.id == flight.id { flights[url] = nil }
            return data
        } catch {
            if flights[url]?.id == flight.id { flights[url] = nil }
            throw error
        }
    }
}

The dictionary is updated before the actor suspends. Another caller can therefore find the existing flight. On completion, the identity check ensures that a delayed waiter for an older flight cannot remove a newer flight stored under the same URL.

There is no completed-data cache here, with 1 narrow exception. A call that lands after the fetch has finished, but before the first waiter resumes and removes the entry, receives that same result instead of starting a new fetch. This loader accepts that, because the data comes from a fetch that has just completed. If the contract must be that every call after completion fetches again, remove the entry from inside the shared task before it returns. In-flight coalescing and caching have different lifetimes. Add storage only after defining its capacity, freshness and invalidation rules.

The injected fetch closure must perform work appropriate to its execution context. Wrapping expensive synchronous image processing in a task does not, by itself, establish a suitable execution policy.

Verify sharing and cleanup

Use a fake fetch that suspends after recording an invocation. Start the first caller, confirm that the fetch has begun, and then start another caller for the same URL. Verify that only 1 underlying fetch was created before completing it.

After both callers receive the result, call again and verify that a new fetch starts. Also test a failed fetch followed by a successful retry. A failed task retained forever would make every later attempt inherit the same failure.

For the cancellation contract, cancel 1 waiting caller and show that another still receives the shared result. Record that the cancelled caller may continue waiting under this deliberately simple policy.

Follow-up, prompt waiter cancellation

Now require a disappearing row to stop waiting immediately, while other rows continue.

That requires tracking waiter lifetimes separately from the shared operation. Discuss cancellation races, completion delivery and whether the last waiter should cancel the underlying task. If the loader supports invalidation, define what an old completion may do after a replacement flight starts.

Do not add a cancellation handler that simply cancels the shared task. That would violate the requirement you agreed to at the beginning.

For more language-level reasoning, see Swift concurrency interview questions.

Task 3, a bounded least-recently-used cache

Candidate brief

Implement a cache with a fixed entry capacity. Reading an entry makes it most recently used. Inserting a new entry beyond capacity evicts the least recently used entry. Updating an existing key changes its value and makes it most recent.

Agree on 0 capacity, missing reads and thread safety. This exercise uses 0 as a disabled cache, missing reads leave order unchanged, and callers must provide synchronisation if they share the value across concurrent access. Values are nonoptional to keep the example's return contract simple.

Reference implementation with an explicit cost

struct LRUCache<Key: Hashable, Value> {
    private let capacity: Int
    private var values: [Key: Value] = [:]
    private var order: [Key] = [] // least recent first

    init(capacity: Int) {
        precondition(capacity >= 0)
        self.capacity = capacity
    }

    mutating func value(for key: Key) -> Value? {
        guard let value = values[key] else { return nil }
        touch(key)
        return value
    }

    mutating func insert(_ value: Value, for key: Key) {
        guard capacity > 0 else { return }
        values[key] = value
        touch(key)
        if order.count > capacity {
            let evicted = order.removeFirst()
            values[evicted] = nil
        }
    }

    private mutating func touch(_ key: Key) {
        order.removeAll { $0 == key }
        order.append(key)
    }
}

This baseline uses an array for recency. Touching an entry and shifting array elements cost linear time in the number of cached entries. It does not meet an expected-constant-time LRU requirement.

For a small bound, you can propose it as a simple baseline and state the cost. If the interviewer requires expected constant-time operations, use a hash map plus a doubly linked list, and discuss ownership of list nodes carefully in Swift. Do not claim an optimisation you have not implemented.

Verify recency rather than just capacity

With capacity 2, insert A and B, read A, then insert C. B should be evicted. A cache that only tracks insertion order will fail that sequence.

Then update A and check that its new value is returned without adding a duplicate recency entry. Test capacity 0, capacity 1 and a missing lookup.

Follow-up, images have different sizes

An entry count does not bound image memory use. If the requirement becomes a cost budget, define what cost represents and evict until the budget is satisfied. Decide what happens when a single item exceeds the budget.

Compressed byte count and decoded-image memory are different measures. Choose the measure that matches the resource you are limiting, and explain what remains outside the cache's accounting.

How I would review the attempt

I would look for a clear contract, a small implementation that follows it, a test that challenges the happy path, and an accurate account of the remaining limitations.

TaskA concrete concernEvidence of repair
SearchOld failures can replace new successControlled late-failure check passes
Shared loadingA consumer cancels everyone's workSeparate waiter and shared-task policies
LRUReading does not change eviction orderRead-A, insert-C sequence evicts B

If you do not finish, state what is implemented and what remains. For example, “Coalescing and retry after failure are checked. Prompt waiter cancellation is not implemented, and the current contract allows that waiter to remain suspended.”

That gives the reviewer a precise result to assess.

Continue with a structured iOS route

iOS Interview Training includes the book, companion code and Guided Practice. Read the free sample and inspect the format before buying.

The implementations in this article are standalone teaching examples, not copies of the paid companion. Use them for a first attempt, then repeat with a changed constraint such as a cleared query, a cancelled row or a cache budget measured in bytes.

To see what a reviewer does with a working answer, read the follow-up decides the senior mobile interview. For the language-mode side of the concurrency code, see Swift 6 strict concurrency migration.

Sources

  1. The Swift Programming Language, Concurrency.
  2. Apple, Task.checkCancellation.

Questions readers ask

© 2026 Mike Salari, Interview Runtime. All rights reserved. Quoting a short excerpt with a link to this page is welcome; republishing the article, in full or in part, is not.

Practice the follow-up, not the first answer.

Interview Runtime is the interview book plus 90 days of Guided Practice: you answer first, see the one gap that would cost the point, then answer again when one fact changes.