In the world of programming, tracking variable changes can often turn into a debugging nightmare. In Xcode, you might find yourself frequently relying on breakpoints and manually tracing the changes in your variables’ values. At times, you might also utilize property observers such as didSet and willSet for this purpose.

But what if I tell you, there’s a powerful tool waiting for you to harness its capabilities: Watchpoints. They allow you to monitor a specific variable or memory address for changes, providing invaluable insights into your program’s execution.

What Are Watchpoints?

Watchpoints are a kind of breakpoint that don’t halt the execution of the program when a line of code is reached. Instead, they pause the program when a specific variable changes its value. This feature becomes incredibly useful when you’re unsure of where or when a variable’s value is being altered in your code.

How to Set a Watchpoint in Xcode

Setting a watchpoint in Xcode is a straightforward process. Let’s walk through it step by step.

Step 1: Set a Breakpoint and Run Your Program

Firstly, you need to set a regular breakpoint in your program and run it. The breakpoint will pause the execution of the program, enabling you to inspect the current state of your variables.

Consider the following code,

struct Employee {
    var salary: Int = 0 {
        didSet {
            print("Salary has been set to \(salary)")
        }
    }
    func changeSalary() {
        var john = Employee()
        john.salary = 5000
        john.salary = 6000
        john.salary = 7000
    }
}

Set the breakpoint in the line john.salary = 5000 and run the program.

Setting a Breakpoint


Step 2: Add a Watchpoint

Once your program is paused, navigate to the debug area (at the bottom of the Xcode window). Here, you’ll see a list of all the variables currently in scope along with their values.

Find the variable you want to add a watchpoint to, right-click it, and select Watch ‘VariableName’. In our case the ‘VariableName’ is replaced by ‘salary’ A watchpoint will be set for that variable.

Setting an Xcode Watchpoint

Step 3: Continue Execution

Now, continue running your program. The execution will pause whenever the value of the watched variable changes, allowing you to inspect the new value and see exactly where in your code the change occurred.
In our case, whenever the value of the property salary changes, the watchpoint will be hit and the program execution will be paused.

Xcode Watchpoint

Conclusion

Watchpoints are a powerful, yet often overlooked feature in Xcode that can significantly improve your debugging process. The next time you’re wrestling with a bug that involves variable value changes, don’t forget about the power of watchpoints - they could be the tool you need to squash that bug swiftly.

References

[1] https://developer.apple.com/videos/play/wwdc2018/412/

About the author