Skip to content

Instantly share code, notes, and snippets.

@PaulTaykalo
Last active November 27, 2016 16:49
Show Gist options
  • Save PaulTaykalo/131e771c581be5cc83b4e0598ca3c968 to your computer and use it in GitHub Desktop.
Save PaulTaykalo/131e771c581be5cc83b4e0598ca3c968 to your computer and use it in GitHub Desktop.
Optional Loggin extension
import Foundation
//
// MARK:- Private
//
class MyAwesomeLogger {
static func log(message: String) {
print(message)
}
}
struct Friend {}
class DB {
static func friend(byName name: String) -> Friend? {
return nil
}
}
//
// MARK: Fun things
//
extension Optional {
func logNil<T>(function: String = #function,
filename: String = #file,
line: Int = #line,
message: String = "not found",
context: T
) -> Wrapped? {
if self == nil {
let messageToLog = "\((filename as NSString).lastPathComponent):\(line) \(function) \(context) \(message)"
MyAwesomeLogger.log(message: messageToLog)
}
return self
}
}
func findFriend(byName name: String) -> Friend? {
return DB.friend(byName: name)
.logNil(context: name) // <-- Here is the trick
}
findFriend(byName: "Awesome")
// Output
// playground50.swift:40 findFriend(byName:) Awesome not found
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment