Skip to content

Instantly share code, notes, and snippets.

@Neradoc
Last active April 15, 2016 05:23
Show Gist options
  • Save Neradoc/86b3468a1612f8e1d57db20ab2fab5ae to your computer and use it in GitHub Desktop.
Save Neradoc/86b3468a1612f8e1d57db20ab2fab5ae to your computer and use it in GitHub Desktop.
Example code for emoji-fueled logs with type safety
// A logging function that uses emojis to make the output prettier
// - one clear way to specify the type of display we want
// - provide type safety for the printed parameter
// - no weird operator syntax ;-)
// Inspired by "Swift: Pretty in print()" by Andyy Hope
// part 1: https://medium.com/p/64832bb7fafa/
// part 2: https://medium.com/p/640cea920653/
// Note: Ideally you would give the object to print first, so the completion
// can give the valid display modes available for that type. But I don't think
// there is any simple way to do that.
// This one is private, so the name is of no importance
// Don't forget to set a DEBUG CFlag, so it's all optimized away in production
private func __log<T>(type:String,_ input:T) {
//#if DEBUG
print(type,input)
//#endif
}
// Use the parameter's tag to indicate the type of log
// Use the type to guarantee type safety as appropriate
// Everything about a type of logging is on a single line, making it easy to add one
// - write the type name only once
// - write the emoji on the same line
// - possibility to use the same type name with multiple types
// By the way, we don't want to clash with the math "log" function in auto complete
// so, let's add some letter that makes it easy for XCode
func llog(ln input: String) { __log("✏",input) }
func llog(url input: String) { __log("🌏",input) }
func llog(error input: NSError) { __log("❗",input) }
func llog(any input: Any) { __log("⚪",input) }
func llog(obj input: AnyObject) { __log("◽",input) }
func llog(date input: NSDate) { __log("🕒",input) }
// here we even specify how to print a url:
func llog(url input: NSURL) { __log("🌏",input.absoluteString) }
// Now here are some examples
import Foundation
let aString = "This is a string"
let url = "http://www.somewhere.com"
let nsurl = NSURL(string: url)!
let date = NSDate()
let error = NSError(domain: "A bad thing happened", code: 101, userInfo: nil)
llog(ln : aString)
llog(url : url)
llog(url : nsurl)
llog(date : date)
llog(any : ["Key":1337])
llog(error: error)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment