Day 64 - 100 Days of Swift

3 minute read

Project 18 (part 1)

Day 64 is the first part of the eighteenth project. It is a technique project about debugging, which means you don’t actually build anything or even write much code today. You just go over a few techniques that are useful for debugging: print, assert breakpoints and conditional breakpoints.

You use print to print out a message to the console. It is the simplest version of debugging and is available pretty much anywhere you can write code. In Swift (as in most languages) you can interpolate values or the result of code into the message that is printed out. print also gives you a separator and a terminator parameter, if you want to print stuff in between, or at the end of your printed elements:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
print("Hello Bob")
// prints "Hello Bob"

print("Hello", "Bob")
// prints "Hello Bob"

let name = "Bob"
print("Hello \(name)")
// prints "Hello Bob"

print("Hello", name)
// prints "Hello Bob"

print("Hello", name, separator: "-")
// prints "Hello-Bob"

print("Hello", name, terminator: ".\n")
// prints "Hello Bob."

You use assert to check your assumptions about what a value should be at any point in the code. You give it a condition to evaluate and a message to print if it fails. They will cause your app to crash in development, but they get removed when the app is compiled to ship.

1
2
3
4
5
6
7
8
9
assert(name == "Bob", "Who are we even talking to?")
// Passes because name is "Bob"

assert(1 == 1, "Something is wrong with the world")
// Passes because 1 does equal 1

assert(1 == 2, "Something is wrong with my math")
// Fails because 1 does not equal 2
// Prints "Assertion failed: Something is wrong with my math: file .../100-Days-Swift/Project18/Project18/ViewController.swift, line 43"

You set breakpoints in Xcode on the line number. Clicking on the line number will add a little blue arrow and the code will pause on that line when it is hit. You can execute code in the lldb console when the code is paused. You can see the current value of all your variables. You can see the back trace of what code called the code you’re paused on. You can see if a particular line of code is getting hit. You can add conditions so that it will only stop on the break point if the conditions are met. You can even add actions that will automatically execute when a break point is hit. There are lots of options, and it can be really complex, but most of the time I find that I only need the most basic breakpoint options.

Screenshot of breakpoint editor.

You can find my version of this project at the end of day 64 on Github here.