Skip to content
Tutorials Center
My learning

Topics

Lesson 142 of 146 ยท Practice

Common Swift Mistakes

The Swift mistakes beginners and professionals make - force unwraps, index traps, retain cycles, value semantics surprises and Swift 6 concurrency errors - with the real compiler messages and fixes.

Swift is designed so that the compiler catches mistakes before your program runs. The price is that the compiler talks to you a lot, and its messages are not always obvious the first time you see them. This lesson collects the mistakes that come up again and again, shows each one failing with the real message from the compiler or the runtime, and then shows the fix.

The mistakes fall into four groups. Compile-time errors are the friendly ones: the program does not build, and the message says where. Runtime traps are harder, because the program builds and then stops. Memory and semantics bugs do not produce any message at all; the program just behaves in a way you did not expect. Concurrency errors are a special case of the first group that Swift 6 adds. Read the error text carefully each time: the real message is part of the lesson.

The programs on this page are compiled with optimizations on (-O). That has two visible effects: assert is removed, and traps such as an array index out of range or integer overflow stop the process with a signal and a backtrace but no message text. Failures from fatalError, try!, as! and uncaught errors do print a message on stderr, but force unwraps of nil are silent too, as you will see below.

Compile-time errors you will meet in your first week

Four of the most common messages, all in one file. The compiler reports every independent error in a single run, so you see them together.

Swift Four compile errors at once (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler lists four errors, one per function:

TEXT
main.swift:9:20: error: cannot convert value of type 'Int' to expected argument type 'Double'
main.swift:14:12: error: cannot use mutating member on immutable value: 'origin' is a 'let' constant
main.swift:18:12: error: 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
main.swift:24:13: error: call can throw, but it is not marked with 'try' and the error is not handled

The first two even come with a note that suggests the fix, such as change 'let' to 'var' to make it mutable.

Each message points to a rule worth knowing:

  1. No implicit numeric conversion. Swift never converts Int to Double by itself, because silent conversions hide precision loss and overflow. Convert on purpose: total / Double(count).
  2. let means constant, including for value types. A struct stored in a let cannot be mutated; declare it with var if the method is mutating. Classes behave differently, because a let reference still allows changing the object's properties.
  3. Strings are not indexed by integers. A Character can be many bytes long, so word[2] would need to scan from the start. Use word[word.index(word.startIndex, offsetBy: 2)], or convert to an array, or use word.dropFirst(2).first. See the strings lesson.
  4. Calls that can throw need try. The mark makes failure visible at the call site. Handle the error with do/catch, or use try? to get an optional.

Here are the corrected versions:

Swift The same four functions, fixed

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Note that thirdLetter now returns an optional: a word with fewer than three letters has no third letter, and the type says so. Fixing an error often improves the design.

Force unwraps and other deliberate crashes

The exclamation mark means "I promise this is not nil". If you break the promise, the program stops. The runtime message is blunt and the exit code is a signal:

Swift Force unwrapping nil (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The program stops at once. Because this build is optimized, there is no Fatal error: Unexpectedly found nil while unwrapping an Optional value text. The run ends with Program crashed: Illegal instruction, which is signal 4 (SIGILL), and a backtrace whose first line, main + 641 in binary, shows where it happened. In a debug build in Xcode you would see the readable message; do not count on it.

The input was not a number, so Int(line) is nil, and the ! turns that into a crash. The fix is to decide what should happen for bad input. With an if let or guard let, the bad case becomes an ordinary code path:

Swift Handling the bad input instead

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The rule of thumb: use ! only for values that your own code just made certain, such as a regular-expression literal or a hard-coded URL string, and where a nil would be a bug. Never use it on input from users, files or the network. The same advice applies to as! (use as?) and try! (use do/catch). See optionals and type casting.

Index out of range and integer overflow

Two traps give no message in optimized builds, only a signal. An array index that does not exist stops the program, and so does integer arithmetic that does not fit in the type:

Swift Index out of range (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

looking up 5 is printed, then the process dies with the same Illegal instruction crash. The array has three elements, so index 5 does not exist.

Swift chooses to trap rather than read memory that is not yours. In C the same mistake would silently read garbage, and security bugs follow. The fixes are to check first, or to use APIs that return optionals:

Swift Safe lookups and explicit overflow handling

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Choose the behavior you want: trap (a plain +), wrap (&+), report (addingReportingOverflow), fail (Int8(exactly:)) or saturate (Int8(clamping:)). Just never leave it to chance. For preconditions in your own code, precondition(index < count) documents the contract and keeps working in optimized builds, while assert disappears. See assertions and preconditions.

Memory: retain cycles

Swift reclaims objects with reference counting. If object A holds a strong reference to B and B holds one back to A, neither count reaches zero and neither is ever freed. No error appears. The only symptom is a deinit that never runs.

The most common way to create a cycle by accident is a closure stored in a property of an object, where the closure uses self:

Swift A retain cycle: deinit never runs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The output is leaky finished and scope ended, and the line leaky deinitialized never appears. Nothing warned you.

downloader owns the closure through onFinish, and the closure owns downloader through its capture of self. When scope() returns, the local variable goes away, but the cycle keeps both alive. The fix is a capture list that makes the closure's reference weak:

Swift Breaking the cycle with a weak capture

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Use [weak self] when the object may be gone by the time the closure runs; the captured self becomes an optional, and the guard let self line unwraps it. Use [unowned self] only when you can prove the object outlives the closure, because an unowned reference to a freed object traps. Closures passed to map or filter do not need this: they are non-escaping and finish before the function returns. The same cycle can occur between two classes that point at each other (a parent with children and a child with parent); make the back-pointer weak. See memory management with ARC and escaping closures.

Value semantics surprises

A frequent source of confusion is forgetting whether a type is a struct or a class. Assigning a struct copies it. Assigning a class instance copies only the reference, so both names see the same object:

Swift Struct copy versus class reference

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The loop variable in for item in list is a copy of each element for a struct, so changing it does nothing to the array. Modify through the index instead, or use map to build a new array. The opposite surprise happens with classes: an array of objects shares the objects, so copying the array does not copy them. Choose the type on purpose; the value versus reference lesson gives the rules.

Swift 6 concurrency errors

Swift 6 turns data races into compile errors. The messages are long, but each follows a pattern: some value is used from two places that might run at the same time without protection. The program below makes three typical mistakes:

Swift Three concurrency errors (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler reports three errors:

TEXT
main.swift:6:5: error: main actor-isolated var 'counter' can not be mutated from a nonisolated context
main.swift:15:13: error: actor-isolated instance method 'deposit' cannot be called from outside of the actor
main.swift:19:17: error: 'async' call in a function that does not support concurrency

In order:

  1. A global mutable variable. counter lives on the main actor in main.swift, but increment() is not main-actor code. Swift cannot prove two tasks will not touch it at the same time. Keep the state in an actor, pass it as a parameter, or protect it with a Mutex.
  2. Missing await on an actor call. Calling an actor method from outside means you may have to wait for the actor to be free, and that waiting is a suspension point, which Swift insists you write down: await account.deposit(5).
  3. An async call in a synchronous function. compute() is not async, so it cannot call fetchValue(), with or without await. Make compute async and write await fetchValue().

The fixed program keeps the counter inside an actor and awaits every async call:

Swift The concurrency errors, fixed

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Resist the urge to silence the compiler. nonisolated(unsafe) and @unchecked Sendable exist, but each one is a promise you make and the compiler cannot check. Reach for an actor or a Mutex first. See Sendable and data races and synchronization and shared state.

Mistakes that print nothing wrong

  • Printing a dictionary or set and expecting a fixed order. Swift randomizes the order per run for security. Sort before printing: dict.sorted { $0.key < $1.key }.
  • Interpolating an optional. print("age: \(age)") with age: Int? prints Optional(30) and the compiler warns that interpolation "produces a debug description for an optional value". Unwrap first, or use ?? "unknown".
  • Comparing floating-point numbers with ==. 0.1 + 0.2 == 0.3 is false. Compare with a tolerance, or use Decimal for money.
  • Using count == 0 instead of isEmpty. Both work for arrays, but isEmpty is always constant time and states the intent.
  • Treating Substring as a long-lived String. A substring keeps the whole original string alive. Convert with String(sub) before storing it.
  • Over-using classes. If a type has no identity and no inheritance, a struct is simpler and safer.

A debugging checklist

  1. Read the first error only; later ones are often consequences.
  2. Look at the line and column and the little caret under the code. Most messages quote the type that confused the compiler.
  3. For runtime traps, find the line in the backtrace that belongs to your file and ask which assumption failed: "this is not nil", "this index exists", "this arithmetic fits".
  4. When a deinit does not run, look for a closure or a back-pointer that holds self strongly.
  5. When a Swift 6 concurrency error is hard to read, simplify: move the state into an actor and see whether the message goes away.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does Swift reject total / count when total is a Double and count is an Int?

    The compiler reports that it cannot convert an Int to the expected Double. Explicit conversion keeps precision loss visible.
  2. 2. Which is the safest way to read the element at a possibly invalid index of an array?

    Checking indices.contains first turns an out-of-range trap into a normal branch. Arrays have no at method and subscripts do not throw or return optionals.
  3. 3. What is the symptom of a retain cycle?

    Reference counts never reach zero, so objects stay alive silently. Use [weak self] or a weak back-pointer to break the cycle.
  4. 4. After var b = a where a is a struct, you change b.x. What happens to a.x?

    Structs have value semantics: assignment copies. For a class, both names would refer to the same object.
  5. 5. What is the recommended way to share a mutable counter between many tasks in Swift 6?

    An actor serializes access, and the compiler can check that. The unsafe escape hatches only silence the checker.

Summary

  • Read compiler errors from the first one, and use the real message to find the rule: no implicit numeric conversion, let structs are immutable, strings are not integer-indexed, throwing calls need try.
  • Force unwraps, as!, try!, out-of-range indices and overflow stop the program; replace them with if let, guard, indices.contains and the overflow-aware operators.
  • Optimized builds remove assert and print no message for index and overflow traps, so use precondition for checks that must stay.
  • A closure stored in a property that captures self creates a retain cycle; fix it with [weak self], and make parent pointers weak.
  • Structs copy on assignment, classes share; mutate array elements through the index.
  • Swift 6 reports data races as compile errors; keep shared state in actors and await every async call.

Next: Swift for Developers from Other Languages