Last active
November 27, 2016 16:49
-
-
Save PaulTaykalo/131e771c581be5cc83b4e0598ca3c968 to your computer and use it in GitHub Desktop.
Optional Loggin extension
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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