XCUIElementQuery: The Blueprint for Finding UI Elements

An XCUIElementQuery is a recipe for finding UI, not the element itself. It describes a search that runs only when you interact with the result. Use it in XCUITest to locate views for automated tests. The footgun: thinking a query finds an element on creation.
WHY IT EXISTS UI testing requires a reliable way to find and interact with on-screen elements. Hardcoding view references is brittle and fails with dynamic UIs. XCUIElementQuery provides a flexible, descriptive way to locate elements at runtime, even as the UI changes.
THE MENTAL MODEL An XCUIElementQuery is like a database query, not the result set. It's a plan for how to find something. app.buttons["Submit"] doesn't give you the button; it gives you an object that knows how to find a button with the accessibility identifier "Submit" when you need it. The actual search happens later.
HOW IT WORKS You start from the root XCUIApplication object and chain queries to narrow your search. For example, app.tables.cells.containing(.staticText, identifier:"Profile").buttons["Edit"] builds a complex search path. The query is only resolved—meaning the UI tree is actually traversed—when you perform an action (.tap(), .swipeUp()) or check a property (.exists, .isHittable). If no element is found at that moment, the test fails.
WHEN TO USE IT Use XCUIElementQuery for all UI element location in your XCUITest suites. It is the fundamental tool for writing UI tests. You'll use it to find elements to tap, type text into, swipe, or assert their existence.
WHEN NOT TO USE IT Do not use XCUIElementQuery in your main application code. It is strictly part of the XCUITest framework and is not available for production logic. For finding views within your app, you'd use mechanisms like viewWithTag(_:) or direct property outlets.
ONE CANONICAL EXAMPLE A common task is tapping a login button. First, you create the query: let loginButton = app.buttons["Login"]. This line does not find the button and does not fail if it's not on screen. The test only interacts with the UI when you call the action: loginButton.tap(). The test will wait for the element to appear for a short timeout period at the moment .tap() is called. If it's not found then, the test fails.
Read the original → developer.apple.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.