---
title: Screen Objects in Swift | TestingBot
description: After four chapters the sign-in steps exist in three places, and the
  identifier `&quot;tasks.newTitle&quot;` in four. When the sign-in screen changes,
  every…
source_url:
  html: https://testingbot.com/resources/courses/xcuitest/screen-objects
  md: https://testingbot.com/resources/courses/xcuitest/screen-objects.md
---

Course

[XCUITest Tutorial: iOS UI Testing in Swift](https://testingbot.com/resources/courses/xcuitest)

Chapter 6 of 11

1. [1 XCUITest Tutorial: iOS UI Test Automation in Swift](https://testingbot.com/resources/courses/xcuitest)
2. [2 Add a UI Test Target and Run Your First Test](https://testingbot.com/resources/courses/xcuitest/add-a-ui-test-target)
3. [3 Element Queries and Accessibility Identifiers](https://testingbot.com/resources/courses/xcuitest/queries-and-accessibility-identifiers)
4. [4 Interactions and Assertions](https://testingbot.com/resources/courses/xcuitest/interactions-and-assertions)
5. [5 Waiting Without sleep(): waitForExistence and Predicates](https://testingbot.com/resources/courses/xcuitest/waiting-without-sleep)
6. [6 Screen Objects in Swift](https://testingbot.com/resources/courses/xcuitest/screen-objects)
7. [7 Launch Arguments and Environment: Control App State](https://testingbot.com/resources/courses/xcuitest/launch-arguments-and-environment)
8. [8 Build for Testing: The App and the Test Runner](https://testingbot.com/resources/courses/xcuitest/build-for-testing)
9. [9 Run XCUITest on Real iPhones with TestingBot](https://testingbot.com/resources/courses/xcuitest/run-on-testingbot)
10. [10 XCUITest in CI with GitHub Actions](https://testingbot.com/resources/courses/xcuitest/ci-github-actions)
11. [11 XCUITest Knowledge Check](https://testingbot.com/resources/courses/xcuitest/knowledge-check)

[Exit course](https://testingbot.com/resources/courses)

 Chapter 6 of 11 Intermediate 6 min read 2 quick checks Updated Nov 2026 

# Screen Objects in Swift
On this page
1. [The two screens](https://testingbot.com#the-two-screens)
2. [Design decisions, and why](https://testingbot.com#design-decisions-and-why)
3. [Keeping screen objects healthy](https://testingbot.com#keeping-screen-objects-healthy)

After four chapters the sign-in steps exist in three places, and the identifier `"tasks.newTitle"` in four. When the sign-in screen changes, every copy has to change. A **screen object** (the mobile name for a page object) gathers the queries and actions of one screen behind a small Swift type, so tests describe _what_ the user does and the screen object knows _how_.

The idea is the same as in web testing, where the [Page Object Model course](https://testingbot.com/resources/courses/page-object-model) covers it in depth. This chapter shows how it looks in Swift with XCUITest and where Swift's features help.

## The two screens[#](https://testingbot.com#the-two-screens)

`Screens.swift` in the UI test target:

```swift
import XCTest

struct LoginScreen {
    let app: XCUIApplication

    var email: XCUIElement { app.textFields["login.email"] }
    var password: XCUIElement { app.secureTextFields["login.password"] }
    var submit: XCUIElement { app.buttons["login.submit"] }
    var error: XCUIElement { app.staticTexts["login.error"] }

    @discardableResult
    func signIn(email: String, password: String) -> TaskListScreen {
        self.email.tap()
        self.email.typeText(email)
        self.password.tap()
        self.password.typeText(password)
        submit.tap()
        let list = TaskListScreen(app: app).waitUntilShown()
        // After a successful sign-in iOS may offer to save the password.
        // The sheet sits on top of the list and swallows the next tap.
        // A tap while it is still sliding in can miss, so tap until it is gone.
        let notNow = app.buttons["Not Now"]
        if notNow.waitForExistence(timeout: 3) {
            for _ in 0..<3 where notNow.exists {
                notNow.tap()
                _ = notNow.waitForNonExistence(timeout: 3)
            }
            XCTAssertFalse(notNow.exists, "The Save Password sheet did not go away")
        }
        return list
    }
}

struct TaskListScreen {
    let app: XCUIApplication

    var title: XCUIElement { app.navigationBars["Tasks"] }
    var newTitle: XCUIElement { app.textFields["tasks.newTitle"] }
    var addButton: XCUIElement { app.buttons["tasks.add"] }
    var openCount: String { app.staticTexts["tasks.count"].label }
    var rows: XCUIElementQuery { app.buttons.matching(identifier: "task.row") }

    func row(_ title: String) -> XCUIElement { app.buttons[title] }

    func waitUntilShown(file: StaticString = #filePath, line: UInt = #line) -> Self {
        XCTAssertTrue(title.waitForExistence(timeout: 10),
                      "Task list did not appear", file: file, line: line)
        return self
    }

    @discardableResult
    func add(_ text: String) -> Self {
        newTitle.tap()
        newTitle.typeText(text)
        addButton.tap()
        return self
    }

    @discardableResult
    func toggle(_ text: String) -> Self {
        row(text).tap()
        return self
    }
}
```

And the test that uses them, the one from the introduction:

```swift
import XCTest

final class ScreenObjectTests: XCTestCase {
    let app = XCUIApplication()

    override func setUpWithError() throws {
        continueAfterFailure = false
        app.launchArguments = ["-resetState"]
        app.launch()
    }

    func testSignInAndAddTwoTasks() throws {
        let list = LoginScreen(app: app)
            .signIn(email: "anna@example.com", password: "secret")

        list.add("Buy milk").add("Call Anna").toggle("Buy milk")

        XCTAssertEqual(list.rows.count, 2)
        XCTAssertEqual(list.openCount, "1 open")
    }
}
```

It passed on iOS 26.4 and iOS 27 simulators and on the real iPhones in chapter 8. The Save Password handling from chapter 4 now lives in exactly one place: every test that signs in gets it for free.

## Design decisions, and why[#](https://testingbot.com#design-decisions-and-why)

**Structs holding the app.** A screen object has no state of its own beyond the `XCUIApplication`, so a struct is enough. Creating one is free; there is no reason to share instances between tests.

**Computed properties, not stored elements.** `var email: XCUIElement { app.textFields["login.email"] }` builds the query each time it is read. Since queries resolve lazily anyway (chapter 2), a stored `let` would also work, but computed properties make it obvious that nothing is cached and keep the type trivially constructible.

**Actions return the next screen.** `signIn` returns a `TaskListScreen`, so the test reads as a user journey and the compiler stops you from calling `add` on the sign-in screen. Actions that stay on the same screen return `Self` for chaining. `@discardableResult` keeps the compiler quiet when a test does not use the return value.

**Waiting belongs to the screen.** `signIn` does not return until the list is really showing and the system sheet is dealt with. Tests no longer need to know that sign-in is slow; if it gets slower, one timeout changes.

**Assertions report the test's line.** `waitUntilShown` takes `file: StaticString = #filePath, line: UInt = #line` and passes them to `XCTAssertTrue`. When the list does not appear, Xcode marks the line _in the test_ that called `waitUntilShown`, not a line inside `Screens.swift` that every test shares. Do this for every assertion inside a helper.

**Assertions about outcomes stay in the test.** The screen object exposes `rows` and `openCount`; the test decides what they should be. A screen object that asserts "there are two rows" can only be used by tests that expect two rows.

A helper method in a screen object contains `XCTAssertTrue(title.waitForExistence(timeout: 10))`. When it fails, Xcode highlights that line in the helper for all 40 tests that use it. What change makes the failure point at the calling test?

 Replace the assertion with `precondition` Add `file: StaticString = #filePath, line: UInt = #line` parameters and pass them to the assertion Set `continueAfterFailure = true` Move the helper into an extension of `XCTestCase`

XCTest assertions accept the file and line to report. Default arguments capture the caller's location, so the failure appears in the test that called the helper. `precondition` crashes the runner, and moving the code does not change where the assertion is reported.

## Keeping screen objects healthy[#](https://testingbot.com#keeping-screen-objects-healthy)

- **One screen object per screen or major component** , not per test. A reusable component such as a tab bar or a date picker can have its own type that several screens return.
- **Name methods after user intent** : `signIn`, `add`, `toggle`, not `tapSubmitButton`.
- **Expose elements when tests need to check them** (`error`, `rows`), but avoid adding a property for every view on the screen "just in case".
- **Keep identifiers in one place.** If both the app and the tests should use the same strings, a small enum compiled into both targets works; in this course the strings appear only in the screen objects, which is usually enough.

A colleague adds `func assertTwoRows()` to `TaskListScreen`. What is the better design?

 Keep it, and add `assertThreeRows()` when another test needs three Move the assertion into `add()` so every add checks the count Expose `rows` (or a count) and let each test assert the number it expects

The expected outcome belongs to the test. Screen objects that hard-code expectations multiply or become wrong for the next test. Hiding a count check inside `add()` breaks any test that starts with seeded data.

Next: the tests still start the app through the sign-in screen even when they are not about signing in. Launch arguments fix that.

[Previous · Chapter 5 Waiting Without sleep(): waitForExistence and Predicates](https://testingbot.com/resources/courses/xcuitest/waiting-without-sleep) [Next · Chapter 7 Launch Arguments and Environment: Control App State](https://testingbot.com/resources/courses/xcuitest/launch-arguments-and-environment)

On this page

1. [The two screens](https://testingbot.com#the-two-screens)
2. [Design decisions, and why](https://testingbot.com#design-decisions-and-why)
3. [Keeping screen objects healthy](https://testingbot.com#keeping-screen-objects-healthy)

Certification

Earn the free, resume-worthy TestingBot XCUITest Certification for this course.

[How it works](https://testingbot.com/resources/courses/xcuitest/certification)
