Skip to content

Instantly share code, notes, and snippets.

@atierian
Created April 9, 2021 18:32
Show Gist options
  • Select an option

  • Save atierian/83b0d3c432ead092a1617c4fb944f600 to your computer and use it in GitHub Desktop.

Select an option

Save atierian/83b0d3c432ead092a1617c4fb944f600 to your computer and use it in GitHub Desktop.
Property Wrapper for debugging. Maintains history with timestamp
@propertyWrapper
struct Versioned<Value> {
private var currentValue: Value
private(set) var history = VersionHistory()
init(wrappedValue: Value) {
self.currentValue = wrappedValue
}
var wrappedValue: Value {
get {
return currentValue
}
set {
history.values.append(.init(currentValue))
currentValue = newValue
}
}
var projectedValue: Self {
return self
}
struct VersionHistory: CustomDebugStringConvertible {
struct ValueContainer {
let timeStamp: Date
let value: Value
init(_ value: Value, timeStamp: Date = Date()) {
self.value = value
self.timeStamp = timeStamp
}
}
var values: [ValueContainer] = []
var debugDescription: String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "mm:ssZ"
return values.map {
let ts = dateFormatter.string(from: $0.timeStamp)
return "[\(ts)] \($0.value)"
}.joined(separator: "\n")
}
}
}
struct User {
@Versioned var name: String = ""
}
var user = User()
user.name = "John"
user.name = "Michael"
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
user.name = "Jane"
print(user.$name.history)
}
//[13:09-0400]
//[13:10-0400] John
//[13:11-0400] Michael
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment