Member-only story
Precondition, Assert, Fatal Error, or Guard in your Swift Code
Similar, but not quite the same
If you want to stop your code from crashing, or if you don’t want a function to complete if it does not have a variable
set as you desire. But what about whether you want to perform actions in production or development code?
For the lowdown, read on!

Difficulty: Beginner | Easy | Normal | Challenging
Prerequisites
Some basic understanding of functions and methods in Swift would be useful (guide HERE).
Terminology
Assert: A function used for internal sanity checks that are active during testing, but are not used in production code
Function: The process of removing unnecessary detail from a problem
Guard: A statement used to transfer program control out of a scope if the condition is not met
Precondition: A function that checks a condition
Scope: The region of a program where a variable is valid
Variable: A named value, that potentially can be changed as the program runs
Precondition
precondition()
Precondition
allows us to check a condition before proceeding with code. That is, if a Condition
stated evaluates to false
the program execution stops.
The one big condition in Precondition
(LOLOLOL) is that it works in production code as well as development code. If the chosen Condition
stated evaluates to false
precondition will stop the executing code, and log a chosen message
func testPrecondition(willRun: Bool) {
precondition(willRun)
print ("The function /(#function) completed")
}
testPrecondition(willRun: true) // The function testPrecondition(willRun:) completed
testPrecondition(willRun: false) // Precondition failed: file PreconditionAssertGuard.playground, line 6
We can also add a message to allow
func testPrecondition(willRun: Bool) {
precondition(willRun, "Must set willRun to true")
print ("The function /(#function) completed")
}
testPrecondition(willRun: true)…