Browse Questions
  • Subscribe to keyboard notifications to adjust your layout when the keyboard appears or hides, so it doesn't cover your input fields.
  • These four declarations differ in two dimensions: whether the array itself is optional, and whether the elements inside are optional.
  • All three are test doubles — fake objects used in place of real dependencies — but with different roles.
  • Sendable is a protocol that marks a type as safe to share across concurrency domains (actors, tasks).

Answer: All three are test doubles — fake objects used in place of real dependencies — but with different roles.

  • Stub — returns hardcoded values, no behaviour verification
  • Mock — verifies that specific methods were called
  • Spy — wraps real implementation, records calls for later verification

Code Example:

protocol AnalyticsService {
    func track(_ event: String)
}

// Stub — just returns values, doesn't verify calls
class StubAnalytics: AnalyticsService {
    func track(_ event: String) { }  // does nothing
}

// Mock — verifies interactions
class MockAnalytics: AnalyticsService {
    var trackedEvents: [String] = []
    func track(_ event: String) {
        trackedEvents.append(event)
    }
}

// In test
func test_login_tracksEvent() {
    let analytics = MockAnalytics()
    let viewModel = LoginViewModel(analytics: analytics)
    viewModel.login(username: "alice", password: "pass")
    XCTAssertEqual(analytics.trackedEvents, ["login_success"])
}