Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Debug with Asserts & Preconditions in Swift
Written by Team Kodeco

Swift provides two ways to check for invalid conditions during development and debugging, assert and precondition.

assert is used to check for a condition that must be true in order for the program to continue executing. If the condition is false, a message is printed to the console and the program terminates. assert is only executed in debug builds and is disabled in release builds.

Here is an example of using assert:

func divide(_ dividend: Int, by divisor: Int) -> Int {
  // Assert that the divisor is not zero
  assert(divisor != 0, "Divisor cannot be zero.")
  return dividend / divisor
}
divide(10, by: 0) // Assertion failed: Divisor cannot be zero.

precondition is similar to assert, but it’s executed in both debug and release builds. It’s intended to check for conditions that must be true for the program to continue executing, but that are not necessarily programming errors.

Here is an example of using precondition:

func processData(_ data: [String], maxSize: Int) {
  // Precondition that the data array is not larger than maxSize
  precondition(data.count <= maxSize, "Data array is too large.")
  // Process the data
}
processData(["uno", "dos", "tres", "quatro"], maxSize: 3) // Precondition failed: Data array is too large.

It’s important to note that using assert and precondition should be used sparingly and only for truly exceptional conditions. They should not be used for general error handling or control flow.

You can think of assert and precondition as guardrails on a road. They are there to prevent you from going off the road in an emergency, but they should not be used to guide you on the road itself. Instead, it is better to use error handling techniques such as try-catch or using a Result type.

© 2024 Kodeco Inc.