When doing some light debugging most of us tend reach for the good old print() statement right? Yeah, it's just me π
You might add some &&& or === to make your print REALLY stand out from all that output, but after a while it gets really hard to find anything in there. That is where this helper method comes in!
And also, EMOJIS! π
I found this awesome post by Andyy Hope where he really goes into detail how everything works, so if you are interested I recommend going over that whole post. It has 2 parts, and is WELL worth a read! π€
For all of you anxious to try it out right away, behold this helper method. β¬οΈ
Create a new Swift file in your project, and paste this code:
import Foundation
enum log {
case ln(_: String)
case obj(_: String, _: Any)
case error(_: Error)
case url(_: String)
case any(_: Any)
case date(_: NSDate)
}
postfix operator /
postfix func / (target: log?) {
guard let target = target else { return }
func log<T>(_ emoji: String, _ string: String = "", _ object: T) {
#if DEBUG
print(emoji + "\(string)β" + " " + "\(object)")
#endif
}
switch target {
case .ln(let line):
log("βοΈ", "", line)
case .obj(let string, let obj):
log("π¦", string, obj)
case .error(let error):
log("βοΈβοΈβοΈ", "", error)
case .url(let url):
log("π", "", url)
case .any(let any):
log("βͺοΈ", "", any)
case .date(let date):
log("β°", "", date)
}
}
To make use of that "DEBUG" flag, find the following:
- Go to your Project Settings
- Open Build Settings
- In the search, type "Flag"
- Open Swift Compiler - Custom Flags and Active Compilation Conditions
- For Debug insert a value -> "DEBUG"
And now for the fun part! Anywhere in your code use this
log.ln("So long PRINT! Been nice knowin' ya!")/
That prints: βοΈβ So long PRINT! Been nice knowin' ya!
!Important that little / at the very end is very important. That is a postfix operator and without it the log won't print out.
Andyy goes over that in detail in his post so head on there if you are interested how all that works.
You can even use your own character but Andyy recommended it and who am I to doubt Andyy π
Other available logs
Input | Output |
---|---|
log.ln("Text")/ |
βοΈβ Text |
log.obj("My Object", Object)/ |
π¦ My Object β Object Properties |
log.error(error)/ |
βοΈβοΈβοΈβ Error Properties |
log.url("undeadpixel.dev")/ |
π β undeadpixel.dev |
log.date(Date())/ |
β° β 2020-04-25 17:45:14 +0000 |
log.any("Whatever you want")/ |
βͺοΈ β Whatever You want |
It is also quite easy to spot the logs that you added. Sometimes when I want to search over the project for a specific print and I type "print(" in the searchBar, all of the prints from every file are there. Now number of results is far narrower so my own code is easier to spot! π³
That's it! Feel free to modify the helper and add your own emoticons or customise it to your hearts content!
Thank you for reading, you superb person! β₯οΈ
Get in touch on Twitter
Cheers! π»
Top comments (0)