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.

  1. Add a breakpoint.
  2. Add a breakpoint action.
  3. Choose Log Message from the breakpoint action menu.
  4. Enter what you want to print in the text field.
  5. 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.

enabled 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.

breakpoint editor

Click the Add Action button to add a breakpoint action.

Printing Text

Clicking the Add Action button expands the breakpoint editor.

breakpoint action 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.

Related Reading

Get the Swift Dev Journal Newsletter

Subscribe and get exclusive articles, a free guide on moving from tutorials to making your first app, notices of sales on books, and anything I decide to add in the future.

    We won't send you spam. Unsubscribe at any time.