You're using print() wrong!
It's likely that the first line of Swift you wrote went something like this:
print("Hello, world!")
I'm telling you today that you're doing it wrong.
What's wrong with print statements!?
When you print in Swift, you send a text stream to an output device (i.e. the console screen).
This is extremely useful for debugging, but when used in production there are 2 major problems:
1. Security
2. Inefficiency
1. What are the security issues with print()?
When printing to the console, the output is accessible to your app's users - if a bad actor knows what she is doing, she can connect her device to a computer and read the live print statements of running apps.
As a side note - the exact same is true with your app's network calls by using Charles Proxy, so make sure not to send any sensitive data to the client!
It's very easy to leave print statements for debugging forgotten about printed out in a live app, which can lead to all kinds of security headaches.
Therefore you don't want to be printing anything in a live app on the App Store.
2. Why is print() inefficient?
If you look into the Swift source code, you will find that printing in Swift is based on the C vprintf function.
Scroll down to view it in all its glory - over 2000 lines of C code. Rendering glyphs to a console doesn't come cheap!
Every time you leave a print() statement in your production code, this is what you're running. It's the reason why whenever you are debugging an algorithm with many iterations, the execution seems to slow down massively - a lot of work is being done simply to render the debug statements to the console.
Compiler flags to the rescue!
So you you should understand that printing is bad to do in production apps. But there's a really useful way in Swift to prevent this: c ompiler flags.
Compiler flags are utilised as part of the (very interesting) Swift compilation process, and tell the compiler to ignore or use code based on the environment you are in:
#if DEBUG e xecutes the following code only if the app is in a debug build.
#if RELEASE e xecute the following code only if the app is in a release build.
Don't forget #endif at the end of the code you want to flag!
An efficient print() function
With these flags, we can create a simple function that I use in every single codebase whenever I want to print something:
vprintf in all its glory
Finally, as promised, here's the source code for vprintf. Happy hacking!
Comments
Post a Comment