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

Swift coding interview practice without Xcode

Practise the language and algorithm part of a Swift round in a small environment, then add the app integration the round asks for.

Engraving of a plain slate and chalk, a small sponge beside it.

In short

  • Choose the smallest environment that matches the round, and verify its capabilities before the attempt.
  • Preserve first-appearance order with a set for membership and an array for presentation.
  • Use a head index for a queue instead of repeatedly removing the first array element.
  • Test the contract with deterministic fixtures, including cycles and an absent start vertex.
  • Keep app integration practice separate from standard-library coding practice.

Your Swift solution needs 1 function, a collection and a few checks. Opening an iOS app project adds a simulator, lifecycle and UI that the problem did not ask you to build.

For language and algorithm practice, you can use a Swift command-line environment or an appropriate browser runner. The important preparation is to understand what that environment provides and to make the relevant code work there.

This guide separates standard-library coding from iOS integration, then gives you 2 small exercises you can attempt without an app project. They are original training tasks, not questions attributed to a particular company.

If the actual interview requires an Xcode project, UIKit or SwiftUI, rehearse that format too. A pure Swift solution cannot establish that an app feature integrates correctly with its UI and lifecycle.

Choose the smallest environment that matches the round

Swift's official getting-started material supports command-line development and Swift Package Manager on supported platforms.[1] A browser environment may provide a different compiler, operating system and set of libraries from local Xcode.

Work you need to practiseSuitable starting pointSeparate verification
Collection transformationsSwift file or executable packageActual round's version and input contract
Algorithms and data structuresStandard-library runnerTime, memory and language constraints
Foundation-dependent parsingRunner with the required modulePlatform and API availability
Async state logicCompatible concurrency environment and harnessOwnership, cancellation and completion ordering
UIKit or SwiftUI integrationAppropriate Apple SDK and hostUI behaviour, lifecycle and device conditions

Do not assume that a language dropdown gives you the frameworks, test discovery or execution model of an iOS project. Verify the relevant capability instead of discovering its absence halfway through the attempt.

Start with a file that runs

For a single-file local rehearsal, create main.swift, confirm the installed compiler and run a tiny program before adding the exercise.

print("Swift practice environment is ready")

With an installed toolchain that provides these commands, a simple compiled workflow looks like this.

swift --version
swiftc main.swift -o practice
./practice

For several source files or a normal package test target, use an executable Swift package and the corresponding build or test commands. The official command-line guide explains that route.[2]

Keep 1 entry-point strategy. A top-level main.swift and a separate @main declaration should not both define the same executable's entry. Copying a snippet into the wrong harness can create an environment error unrelated to its algorithm.

In a browser, first find how to run the code, read output and inspect the language information. Then perform the same small smoke check. An environment that compiles once is a better starting point than a large file with several unverified assumptions.

Exercise 1, remove duplicate IDs without losing order

Candidate brief

Given an array of string identifiers, return each identifier once, preserving its first appearance. Use Swift's normal String equality. Do not sort the input.

Ask whether empty strings are valid identifiers and whether case or normalisation requires a separate rule. For this exercise, every string is a valid input and the normal equality semantics are intentional.

Attempt the function before reading the implementation.

func orderedUniqueIDs(_ ids: [String]) -> [String] {
    var seen = Set<String>()
    var result: [String] = []

    for id in ids {
        if seen.insert(id).inserted {
            result.append(id)
        }
    }
    return result
}

The set tracks membership; the array records presentation order. Constructing an array from a set alone would not establish the required first-appearance order. Swift's collection documentation distinguishes ordered arrays from sets and key-value collections.[3]

Under normal hash-table assumptions, this uses a linear number of expected membership operations and storage proportional to the distinct IDs. String hashing and comparison also have costs; "linear" here does not mean every arbitrarily long identifier is processed in constant time.

Use checks that address the contract

precondition(orderedUniqueIDs([]).isEmpty)
precondition(orderedUniqueIDs(["a", "b", "a", "c", "b"]) == ["a", "b", "c"])
precondition(orderedUniqueIDs(["", "", "A", "a"]) == ["", "A", "a"])

These are lightweight executable checks, not a full testing framework. Make failures visible and avoid depending on checks that the chosen build configuration removes.

Follow-up. The input is too large to retain and you are asked to emit unique IDs as they arrive.

You can emit first occurrences incrementally, but exact membership still requires information about previously seen IDs. Discuss memory bounds, a finite retention window or an approximate policy if the requirement allows one. Do not claim that returning a stream makes exact unbounded deduplication free of storage cost.

If you want to repeat tasks like this with feedback, Guided Practice in iOS Interview Training lets you answer realistic prompts, inspect weaknesses, revise your answer and compare attempts.

Exercise 2, traverse a graph without removing the array's first item

Candidate brief

Return the vertices reachable from a starting vertex in breadth-first order. Adjacency lists are ordered arrays. Visit each vertex at most once, including when the graph has cycles.

Treat a start vertex absent from the dictionary as an isolated vertex. Preserve the order supplied by each adjacency list. The algorithm does not depend on iterating the dictionary itself.

func breadthFirstOrder(from start: Int, edges: [Int: [Int]]) -> [Int] {
    var queue = [start]
    var head = 0
    var seen: Set<Int> = [start]

    while head < queue.count {
        let vertex = queue[head]
        head += 1

        for neighbour in edges[vertex, default: []] {
            if seen.insert(neighbour).inserted {
                queue.append(neighbour)
            }
        }
    }
    return queue
}

The head index advances through the array. Repeatedly removing the first element of an array would introduce shifting work; the array API documents that cost.[4]

For the reachable subgraph, describe the usual expected work in terms of visited vertices and inspected edges. This implementation retains processed queue entries until it returns, so its simplicity comes with that memory layout. A reusable long-lived queue may need a different design.

Check cycles and discovery order

let graph = [
    1: [2, 3],
    2: [3, 4],
    3: [1],
    4: [4]
]
precondition(breadthFirstOrder(from: 1, edges: graph) == [1, 2, 3, 4])
precondition(breadthFirstOrder(from: 9, edges: graph) == [9])

Explain why marking a vertex when it is enqueued prevents repeated insertion. Then change the adjacency order and predict the resulting traversal. A deterministic fixture helps you separate graph reachability from the order of presentation.

Follow-up. Return the shortest path to a destination in an unweighted graph.

Extend the design with predecessor information and a termination rule. State the unreachable case and whether you need 1 path or all shortest paths. Keep those requirements separate from the baseline traversal.

Practise Swift strings deliberately

A Swift String is not an integer-indexed array of bytes. Its characters can span multiple encoded units, so algorithms that assume 1 visible character equals 1 byte need a different contract.[5]

Choose the representation that matches the problem. For a task explicitly defined over bytes, work with bytes. For user-perceived characters, account for Character semantics. Converting to an array can make some operations simpler while adding traversal and storage costs.

Do not spend the whole interview debugging a representation assumption you never stated. Ask whether the input is ASCII, arbitrary Unicode text or opaque identifiers, and explain the consequence for your approach.

Keep a short language warm-up for the operations you repeatedly need, such as dictionary defaults, set insertion, sorting, optionals, queue indexing and an explicit error result. Practise those operations independently when syntax is the bottleneck.

Read input from stdin without Foundation

Some runners feed the task through standard input. readLine() is in the standard library and returns nil at the end of input. This example reads a count on line 1 and that many integers on line 2, then prints them through Exercise 1.

func parseInts(_ line: String) -> [Int]? {
    var values: [Int] = []
    for part in line.split(whereSeparator: \.isWhitespace) {
        guard let value = Int(part) else { return nil }
        values.append(value)
    }
    return values
}

if let count = readLine().flatMap(parseInts)?.first,
   let numbers = readLine().flatMap(parseInts),
   numbers.count == count {
    print(orderedUniqueIDs(numbers.map { String($0) }).joined(separator: " "))
} else {
    print("invalid input")
}

Run it with printf '5\n1 2 1 3 2\n' | ./practice and it prints 1 2 3. Splitting on isWhitespace also copes with the carriage return that Windows line endings leave behind.

Without Foundation, trimmingCharacters(in:), components(separatedBy:), String(format:) and exit do not compile, because they come from Foundation or the C library. Use split, isWhitespace and string interpolation instead, and print an error rather than exiting. To find out which case you are in, compile this check.

#if canImport(Foundation)
print("Foundation is available")
#else
print("Standard library only")
#endif

Make expected behaviour visible without a large harness

For a short browser exercise, a function plus a few meaningful checks may be enough to begin. Print the actual value when a mismatch would be hard to diagnose. For a larger local exercise, use a normal test target and retain it with the solution.

Do not add a dependency merely to recover the ergonomics of your normal app project unless the task allows it and the value is clear. If a required data structure is unavailable, tell the interviewer what interface you need and whether implementing it is in scope.

Keep correctness and performance claims distinct. A small fixture checks specific behaviour. It does not establish a production latency target or performance across every input size.

Rehearse the limitations of the target editor

Use the browser or command-line setup for a timed attempt, not just a setup check. Notice whether you rely on autocomplete, file navigation, a debugger or an SDK that will not be present.

If the round uses a browser-based coding pad, compare the provider's documented environment with what you must confirm in the actual session.

Avoid adding modern language features to a solution before verifying that the target compiler supports them. Conversely, do not rewrite a clear solution into awkward legacy code merely because a page title looks old. Inspect the runtime and agree the constraints.

These examples ran locally with Apple Swift 6.3.2 in Swift 5 and Swift 6 language modes. Check SDK availability separately in your interview environment. For the differences between those modes, read the Swift 6 strict concurrency migration guide.

Turn a working function into interview practice

Set a timebox, state the contract aloud, implement a baseline and run an inconvenient case. Then ask for a changed requirement and explain which part must change.

For app-oriented tasks, continue with the iOS coding interview tasks.

For async questions that combine ownership, cancellation and ordering, Swift concurrency interview questions give a useful next step. If you want a structured mobile route alongside language practice, inspect iOS Interview Training and its free sample. A browser coding exercise and a mobile design rehearsal cover different parts of a loop; use both when the employer asks for both.

Sources

  1. Swift, Getting started.
  2. Swift, Build a command-line tool.
  3. Swift, Collection types.
  4. Apple, Array.removeFirst.
  5. Swift, Strings and characters.

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.