0
0
Swiftprogramming~5 mins

Assertions (XCTAssertEqual, XCTAssertTrue) in Swift

Choose your learning style9 modes available
Introduction

Assertions help check if your code works as expected by testing values during development. They stop the program if something is wrong, so you can fix it early.

When you want to check if two values are exactly the same in a test.
When you want to verify a condition is true before continuing.
When writing tests to catch mistakes in your code automatically.
Syntax
Swift
XCTAssertEqual(expression1, expression2, "Optional failure message")
XCTAssertTrue(expression, "Optional failure message")

XCTAssertEqual checks if two values are equal.

XCTAssertTrue checks if a condition is true.

Examples
Checks if numbers or strings are equal.
Swift
XCTAssertEqual(5, 5)
XCTAssertEqual("hello", "hello")
Checks if a condition or boolean variable is true.
Swift
XCTAssertTrue(3 < 5)
XCTAssertTrue(isReady)
Sample Program

This program defines two tests: one checks if 2 + 3 equals 5, and the other checks if 4 is even. If the checks fail, the test will show an error message.

Swift
import XCTest

final class SimpleTests: XCTestCase {
    func testSum() {
        let result = 2 + 3
        XCTAssertEqual(result, 5, "Sum should be 5")
    }

    func testIsEven() {
        let number = 4
        XCTAssertTrue(number % 2 == 0, "Number should be even")
    }
}

SimpleTests.defaultTestSuite.run()
OutputSuccess
Important Notes

Assertions are mainly used in test code, not in regular app code.

Use clear messages to understand why a test failed.

Summary

Assertions check if your code behaves as expected.

XCTAssertEqual compares two values for equality.

XCTAssertTrue checks if a condition is true.