I like the smell of Swift in the morning…

Xcode UITests: How to check if a UISwitch is on

Posted: | Author: | Filed under: Swift, UITests, Xcode | 6 Comments »

A simple scenario: You are writing a UITest that should check if a UISwitch is switched on.

In a UnitTest you would simply do this:

When you are running a UITest you cannot do that, because during a running UITest you cannot access the UISwitch directly. Xcode only gives you access to your app’s UI elements via the XCUIElement class. That class is used for all accessible UI elements so it does not have a isOn property like UISwitch has.

So how do you test that the UISwitch is on?

It’s actually pretty easy, but not really obvious. XCUIElement conforms to XCUIElementAttributes which gives you access to a value property of type Any?

So, as value can literally be Any(thing) I tried to cast it to a Bool, because isOn also is a Bool, right?

Not working! Turns out that when you access a UISwitch in your UITest its value property is of type NSTaggedPointerString. Which is a subclass of NSString and can be cast to String (when you are using Swift). So the Bool isOn value has been mapped to a “0” or “1” String.

To test if the first UISwitch in your current view has been switched on, you can do this in a UITest:


  • 1

    John Bettssaid at

    Hi. Which library are you using?

  • 2

    Jörnsaid at

    Hi John,

    I am not using any library, it’s just Apple’s own XCTest framework.



  • 3

    John Bettssaid at

    Thank you jörn. Do you know how can I work with XCTest framework with java? Do you have some link?

  • 4

    Jörnsaid at

    I am afraid XCTest is for Objective-C / Swift only. I am not a Java Dev, so unfortunately I cannot help you with any links regarding UITests in Java.

  • 5

    John Bettssaid at

    Thank you very much!

  • 6

    Leonsaid at

    That was very helpful thanks!

Leave a Reply