Better Print Statements for Debugging

176 0

So we all do it, or have done it.

You are trying to debug why some piece of code is not working as you expected, it’s a bug. Maybe you got the logic wrong? Is that variable actually populated with what you think it is? Which function is actually going wrong?

We could do it the right way with breakpoints, but no, we throw in some print statements like


print("NOW HERE!")'


print("The value of x is \(x)")

print("Inside myFunc")


But after a while you forget that you have done this somewhere else, now the problem becomes which one is actually printing to the console?

Make It Better

There are a couple of things you can do that would make these print statements more useful.

Did you know that you can print the line number and function name to the console? I do not mean hardcoded, I mean dynamically. Take a look at this.

func myFunction (textEntered: String) {
print("You entered \(textEntered)")

myFunction(textEntered: "Hello There!")

The output would show

”You entered Hello There!”

By simply using #function and #line you are telling the compiler to do just that.

So now you know exactly which function and line is executing (or not!).