test function in swift

To test a function in Swift, you can use the XCTest framework provided by Apple. Here's an example of how to test a simple function that adds two numbers:

main.swift
func add(_ a: Int, _ b: Int) -> Int {
    return a + b
}

class MyTests: XCTestCase {
    func testAdd() {
        XCTAssertEqual(add(2, 3), 5)
        XCTAssertEqual(add(-10, 10), 0)
        XCTAssertEqual(add(0, 0), 0)
    }
}
229 chars
12 lines

In this example, we define a function called add that takes two integer arguments and returns their sum. We also define a test class called MyTests that inherits from XCTestCase. Inside this test class, we define a test function called testAdd.

Inside the testAdd function, we use the XCTAssertEqual function to compare the output of our add function with expected values. If the output of add is equal to the expected value, the test will pass. If not, the test will fail.

To run our tests, we can use the Test Navigator in Xcode. Simply select the test class, click the "Test" button, and Xcode will run all of the test functions in the class. If any of the tests fail, Xcode will display an error message indicating which tests failed and why.

gistlibby LogSnag