Bird
Raised Fist0
iOS Swiftmobile~20 mins

Test-driven development in Swift in iOS Swift - Mini App: Build & Ship

Choose your learning style10 modes available
Build: Simple Counter
A screen with a number display and a button to increase the count. The app is built using test-driven development (TDD) to ensure the counter logic works correctly.
Target UI
-------------------
| Simple Counter   |
-------------------
|                 |
|       0         |
|                 |
|   [Increment]   |
-------------------
Display a number starting at 0
Add a button labeled 'Increment'
When the button is tapped, increase the number by 1
Write a unit test to verify the increment logic before implementing it
Starter Code
iOS Swift
import SwiftUI

struct ContentView: View {
    @State private var count = 0

    var body: some View {
        VStack(spacing: 40) {
            Text("\(count)")
                .font(.largeTitle)
                .accessibilityLabel("Current count")
            Button("Increment") {
                // TODO: Increase count by 1
            }
            .accessibilityLabel("Increment button")
        }
        .padding()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

// TODO: Add Counter class and unit test in separate test target
Task 1
Task 2
Task 3
Solution
iOS Swift
import SwiftUI

class Counter: ObservableObject {
    @Published private(set) var count = 0

    func increment() {
        count += 1
    }
}

struct ContentView: View {
    @StateObject private var counter = Counter()

    var body: some View {
        VStack(spacing: 40) {
            Text("\(counter.count)")
                .font(.largeTitle)
                .accessibilityLabel("Current count")
            Button("Increment") {
                counter.increment()
            }
            .accessibilityLabel("Increment button")
        }
        .padding()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

// Unit Test (in test target)
import XCTest
@testable import YourAppModuleName

final class CounterTests: XCTestCase {
    func testIncrementIncreasesCount() {
        let counter = Counter()
        XCTAssertEqual(counter.count, 0)
        counter.increment()
        XCTAssertEqual(counter.count, 1)
    }
}

We created a Counter class that holds the count and a method increment() to increase it by 1. This class uses @Published so SwiftUI updates the UI when the count changes.

The ContentView uses @StateObject to keep the counter alive and updates the displayed number when increment() is called by tapping the button.

Before implementing the increment logic, we wrote a unit test testIncrementIncreasesCount to check that the count starts at 0 and increases to 1 after calling increment(). This follows test-driven development principles.

Final Result
Completed Screen
-------------------
| Simple Counter   |
-------------------
|                 |
|       1         |
|                 |
|   [Increment]   |
-------------------
User taps 'Increment' button
Number on screen increases by 1 each tap
Stretch Goal
Add a 'Reset' button that sets the count back to 0
💡 Hint
Add a reset() method in Counter class and a new Button in ContentView that calls it

Practice

(1/5)
1. What is the main idea behind Test-driven development (TDD) in Swift?
easy
A. Write tests before writing the actual code
B. Write code first, then write tests later
C. Write tests only after the app is complete
D. Skip tests and focus on UI design

Solution

  1. Step 1: Understand TDD concept

    TDD means you write tests before you write the code that makes those tests pass.
  2. Step 2: Compare options with TDD definition

    Only Write tests before writing the actual code correctly states that tests come before code in TDD.
  3. Final Answer:

    Write tests before writing the actual code -> Option A
  4. Quick Check:

    TDD = Write tests first [OK]
Hint: Remember: Tests come first in TDD [OK]
Common Mistakes:
  • Thinking tests are written after code
  • Believing tests are optional
  • Confusing TDD with UI design
2. Which of the following is the correct way to import the testing framework in a Swift test file?
easy
A. import XCTest
B. import SwiftTest
C. import TestKit
D. import Testing

Solution

  1. Step 1: Identify the official Swift testing framework

    The official framework for testing in Swift is called XCTest.
  2. Step 2: Match the import statement

    Only import XCTest is correct to use XCTest in your test files.
  3. Final Answer:

    import XCTest -> Option A
  4. Quick Check:

    Use XCTest for Swift tests [OK]
Hint: Always import XCTest for Swift tests [OK]
Common Mistakes:
  • Using incorrect or non-existent import names
  • Forgetting to import XCTest
  • Confusing XCTest with other frameworks
3. Given the following Swift test code, what will be the test result?
func testSum() {
  let result = sum(2, 3)
  XCTAssertEqual(result, 5)
}

func sum(_ a: Int, _ b: Int) -> Int {
  return a + b
}
medium
A. Test fails because sum(2, 3) equals 6
B. Test passes but result is 6
C. Test fails due to syntax error
D. Test passes because sum(2, 3) equals 5

Solution

  1. Step 1: Analyze the sum function

    The function adds two integers and returns their sum. sum(2, 3) returns 5.
  2. Step 2: Check the test assertion

    The test asserts that result equals 5, which is true, so the test passes.
  3. Final Answer:

    Test passes because sum(2, 3) equals 5 -> Option D
  4. Quick Check:

    sum(2,3) == 5 passes test [OK]
Hint: Check function output matches XCTAssertEqual value [OK]
Common Mistakes:
  • Assuming sum returns wrong value
  • Confusing test failure with syntax error
  • Ignoring the actual return value
4. Identify the error in this Swift test code snippet:
func testIsEven() {
  let number = 4
  XCTAssertTrue(isEven(number))
}

func isEven(_ n: Int) -> Bool {
  return n % 2 == 1
}
medium
A. XCTAssertTrue is used incorrectly; should be XCTAssertFalse
B. The isEven function returns true for odd numbers, causing test failure
C. The test function name is invalid
D. Missing import XCTest statement

Solution

  1. Step 1: Check the isEven function logic

    It returns true if n % 2 == 1, which means odd numbers, not even.
  2. Step 2: Understand test expectation

    The test expects isEven(4) to be true, but 4 is even, so the function logic is wrong and test fails.
  3. Final Answer:

    The isEven function returns true for odd numbers, causing test failure -> Option B
  4. Quick Check:

    Wrong modulo logic causes test fail [OK]
Hint: Check function logic matches test expectation [OK]
Common Mistakes:
  • Mixing odd/even logic in modulo
  • Misusing XCTAssertTrue vs XCTAssertFalse
  • Ignoring function implementation errors
5. You want to use TDD to create a function that filters out negative numbers from an array. Which sequence of steps follows TDD best?
hard
A. Write tests only for positive numbers, ignore negatives
B. Write the filtering function first, then write tests after it works
C. Write a failing test for filtering negatives, write code to pass test, refactor code
D. Write code and tests simultaneously without order

Solution

  1. Step 1: Understand TDD workflow

    TDD requires writing a failing test first that defines desired behavior.
  2. Step 2: Follow TDD steps for filtering negatives

    Write a test that expects negatives filtered out, then write code to pass it, then improve code.
  3. Final Answer:

    Write a failing test for filtering negatives, write code to pass test, refactor code -> Option C
  4. Quick Check:

    TDD = Test first, code second, refactor [OK]
Hint: Always write failing test before code in TDD [OK]
Common Mistakes:
  • Writing code before tests
  • Ignoring refactoring step
  • Writing incomplete tests
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard