Last active
April 26, 2018 08:55
-
-
Save Gatada/89ab03f125180f675eb6588359a2f979 to your computer and use it in GitHub Desktop.
A useful printing implementation that requires no flags, yet gets removed during compiler optimization for a release build.
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 UIKit | |
import PlaygroundSupport | |
/// Prints the `items` with an optional separator and terminator. | |
/// The benefit of this approach is that all calls will be entirely removed during compiler optimization for release builds. | |
/// Additionally you can provide an optional closure to perform text processing. The processed string gets printed either before or immediately after `message` depending on the returned boolean. | |
/// | |
/// - Parameters: | |
/// - items: Zero or more items to print. | |
/// - separator: An optional string to print between each item; default is a single whitespace. | |
/// - terminator: Optionally provide a string to append to the end; default is a single new line. | |
/// - closure: Used to prepare textual output. The closure must return the string to print, and a boolean to determine if the resulting string should be shown above or after the `message` (but before terminator). | |
public func log(_ items: Any..., separator: String = " ", terminator: String = "\n", unprocessedText closure: (() -> (text: String, showAboveMessage: Bool))? = nil) { | |
assert(logPrint(items, separator: separator, terminator: terminator, unprocessedText: closure)) | |
} | |
// See comment above for log(_:seperator:terminator:closure:) | |
fileprivate func logPrint(_ items: [Any], separator: String, terminator end: String, unprocessedText closure: (() -> (text: String, showAboveMessage: Bool))?) -> Bool { | |
var postfix = "" | |
var output = "" | |
if let processText = closure { | |
let processed = processText() as (text: String, showAboveMessage: Bool) | |
if processed.showAboveMessage { | |
print(processed.text) | |
} else { | |
postfix = processed.text | |
} | |
} | |
var prefix = "" | |
for item in items { | |
output += prefix + String(describing: item) | |
prefix = separator | |
} | |
print(output + postfix, terminator: end) | |
return true | |
} | |
log("Processing", separator: ":", terminator: "… ") { () -> (text: String, showAboveMessage: Bool) in | |
let today = DispatchTime.now().rawValue | |
return (" started \(today) ", false) | |
} | |
print("Done!") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment