Created
August 23, 2021 16:31
-
-
Save JUSTINMKAUFMAN/29d485d63a2a57819cc5ae5fbf1c5851 to your computer and use it in GitHub Desktop.
Function Wrapper Concept
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
/// Implementation | |
typealias AnyFunction = ((Any?, ((Any?) -> (Any?))?) -> (Any?)) | |
@functionWrapper | |
struct Logging { | |
let value: AnyFunction | |
@discardableResult | |
func wrappedFunction(_ arguments: Any?, _ completion: ((Any?) -> (Any?))? = nil) -> Any? { | |
let start = mach_absolute_time() | |
print("[\(#function)][start]\t\t\(seconds(start))") | |
if let completion = completion { | |
return value(arguments, { result in | |
print("[\(#function)][elapsed]\t\t\(seconds(mach_absolute_time() - start))") | |
return completion(result) | |
}) | |
} else { | |
let result = value(arguments, nil) | |
print("[\(#function)][elapsed]\t\t\(seconds(mach_absolute_time() - start))") | |
return result | |
} | |
} | |
init(_ value: @escaping AnyFunction) { | |
self.value = value | |
mach_timebase_info(&timebase) | |
} | |
private var timebase = mach_timebase_info_data_t() | |
private func seconds(_ mach: UInt64) -> Double { | |
(Double(mach * UInt64(timebase.numer)) / Double(timebase.denom)) / 1.0e9 | |
} | |
} | |
/// Examples | |
@Logging | |
func syncFactorAllPrimes(_ input: UInt64) -> [UInt64] { | |
// Do very difficult math problem | |
let result: [UInt64] = [1, 13, 19] | |
print("[\(#function)][result]\t\t\(result)") | |
return result | |
/** | |
Console Output | |
------------------------------------------------------- | |
[syncFactorAllPrimes(_:)][start] 1629735701 | |
[syncFactorAllPrimes(_:)][result] [1, 13, 19] | |
[syncFactorAllPrimes(_:)][elapsed] 682ms | |
------------------------------------------------------- | |
*/ | |
} | |
@Logging | |
func updateServer(_ completion: @escaping (Bool) -> Void) { | |
makePostRequest { didSucceed in completion(didSucceed) } | |
/** | |
Console Output | |
------------------------------------------------------- | |
[updateServer(_:)][start] 1629737925 | |
[updateServer(_:)][elapsed] 93ms | |
------------------------------------------------------- | |
*/ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment