Skip to content

Instantly share code, notes, and snippets.

@pteasima
Created June 20, 2019 18:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pteasima/e07b49509b18b0f5aee619af4f855e8d to your computer and use it in GitHub Desktop.
Save pteasima/e07b49509b18b0f5aee619af4f855e8d to your computer and use it in GitHub Desktop.
ReadOnce
// I wrote this and then decided its an overengineered piece of bullshit code. Just deleting it makes me sad so let it forever take up space on Github
// a property that flips back to its default value when it is read
// TODO: does this have proper value semantics with the class inside? And do we even care?
@propertyWrapper struct ReadOnce<Value> {
init(initialValue: Value) {
defaultValue = initialValue
box = ValueBox(value: initialValue)
}
private let defaultValue: Value
final class ValueBox {
init(value: Value) { self.value = value }
var value: Value
}
private var box: ValueBox
var value: Value {
get {
let result = box.value
box.value = defaultValue
return result
}
set {
box.value = newValue
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment