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.