Ad space (banner)
๐ŸฆSwift Lessons
Lesson 28 / 68

Checking Correctness (Your First Step into Testing)

In this lesson you will learn a simple way to verify behaviour in Swift, taking your first step towards checking that a program is correct. This is for anyone searching for "Swift assert how to use".

assert(condition, message) stops the program and tells you when the condition is false. Checking automatically that a function returns the expected result is the basic idea behind test code.

The sample code checks with an if statement whether add(2, 3) equals 5, printing "Test passed" if it does and "Test failed" if it does not. That is the core idea of testing: confirm the result in code rather than by eye.

A common stumbling block for beginners is checking behaviour manually every time and missing cases. In practice you would use a dedicated framework such as XCTest, but the underlying idea is exactly what you learn here.

Bear in mind too that assertions are a debugging aid during development, not a substitute for real error handling in production.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Swift directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)