0
0
Swiftprogramming~20 mins

Why testing matters in Swift - Challenge Your Understanding

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Testing Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Swift code with a failing test?
Consider this Swift code that tests a function. What will be printed when running this test?
Swift
func add(_ a: Int, _ b: Int) -> Int {
    return a + b
}

func testAdd() {
    let result = add(2, 3)
    if result == 6 {
        print("Test passed")
    } else {
        print("Test failed")
    }
}

testAdd()
ATest failed
BTest passed
CCompilation error
DNo output
Attempts:
2 left
💡 Hint
Check what the add function returns and what the test expects.
🧠 Conceptual
intermediate
1:30remaining
Why is testing important in software development?
Choose the best reason why testing is important.
AIt removes the need for documentation.
BIt makes the code run faster.
CIt helps find bugs early before users see them.
DIt guarantees the software will never fail.
Attempts:
2 left
💡 Hint
Think about how testing affects software quality.
🔧 Debug
advanced
2:00remaining
What error does this Swift test code produce?
Look at this Swift code snippet. What error will it cause when run?
Swift
func divide(_ a: Int, _ b: Int) -> Int {
    return a / b
}

func testDivide() {
    let result = divide(10, 0)
    print("Result is \(result)")
}

testDivide()
ARuntime error: index out of range
BCompilation error: missing return
CNo error, prints 'Result is 0'
DRuntime error: division by zero
Attempts:
2 left
💡 Hint
What happens if you divide by zero in Swift?
🚀 Application
advanced
1:30remaining
How many tests are needed to cover all cases for this function?
Given this Swift function, how many tests do you need to cover all possible outputs?
Swift
func checkNumber(_ n: Int) -> String {
    if n < 0 {
        return "Negative"
    } else if n == 0 {
        return "Zero"
    } else {
        return "Positive"
    }
}
A1 test
B3 tests
C2 tests
D4 tests
Attempts:
2 left
💡 Hint
Think about the different conditions in the function.
Predict Output
expert
2:00remaining
What is the output of this Swift code using a test with assertion?
What will this Swift code print when run?
Swift
func multiply(_ a: Int, _ b: Int) -> Int {
    return a * b
}

func testMultiply() {
    assert(multiply(3, 4) == 12, "Test failed: 3*4 should be 12")
    print("Test passed")
}

testMultiply()
ATest passed
BTest failed: 3*4 should be 12
CNo output
DRuntime error: assertion failed
Attempts:
2 left
💡 Hint
Check if the assertion condition is true.