Replace Swift print Statements with Xcode Breakpoint Actions
When you run into problems with your Swift code, your first instinct may be to add print
statements. There’s nothing wrong with print
statements, but you can also use Xcode breakpoint actions to print to Xcode’s debug console. Using Xcode breakpoint actions instead of print
statements has the following advantages:
- You don’t have to write any code.
- They fire only when debugging.
- You can turn them on and off easily without having to rebuild your project.
Take the following steps to create a breakpoint action equivalent of a print
statement.
- Add a breakpoint.
- Add a breakpoint action.
- Choose Log Message from the breakpoint action menu.
- Enter what you want to print in the text field.
- Select the Automatically continue after running checkbox.
Add a Breakpoint
Click on the left side of Xcode’s editor next to the line of code where you want to set the breakpoint.
The breakpoint appears as a blue arrow in the editor.
Add a Breakpoint Action
Right-click on a breakpoint in Xcode’s editor or in Xcode’s breakpoint navigator (Press Cmd–8) and choose Edit Breakpoint. A popover opens to edit the breakpoint.
Click the Add Action button to add a breakpoint action.
Printing Text
Clicking the Add Action button expands the breakpoint editor.
Choose Log Message from the Action menu. The Log Message action is the equivalent of a Swift print
statement.
If you want to show that you entered a function in your code, enter the text in the text field.
Reached viewDidLoad.
If you want to print the value of a variable, wrap it with the @ character. The following message:
Player X: @player.position.x@
Prints the following in Xcode’s debug console if the x position is 12:
Player X: 12
Automatically Continue
At the bottom of the breakpoint editor is a checkbox to automatically continue after running the breakpoint action. Select the checkbox.
Now if you run your project, the messages will appear in Xcode’s Debug console. You created the equivalent of a print
statement without writing any code.
Turning off Printing
To turn off printing, disable the breakpoint. Click on the breakpoint in Xcode’s source editor to disable the breakpoint. Click a disabled breakpoint to enable it.