Skip to content

Instantly share code, notes, and snippets.

@allevato
Created May 7, 2023 18:22
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 allevato/0bc901c05650fbd681fad11f2967ad8a to your computer and use it in GitHub Desktop.
Save allevato/0bc901c05650fbd681fad11f2967ad8a to your computer and use it in GitHub Desktop.
@propertyWrapper
public struct Resettable<Wrapped> {
private var defaultValue: Wrapped
private var possibleValue: Wrapped?
public var wrappedValue: Wrapped {
get {
return possibleValue ?? defaultValue
}
set {
self.possibleValue = newValue
}
}
public var projectedValue: Self {
get { self }
set { self = newValue }
}
public init(wrappedValue: Wrapped? = nil, default defaultValue: Wrapped) {
self.defaultValue = defaultValue
self.possibleValue = wrappedValue
}
public mutating func reset() {
self.possibleValue = nil
}
}
struct MyThing {
@Resettable(default: 0.5) var factor: Double
@Resettable(default: 0.5) var factor2: Double = 1.0
}
print(MyThing().factor) // 0.5
print(MyThing().factor2) // 1.0
var t = MyThing()
t.factor = 2.0
print(t.factor) // 2.0
t.$factor.reset()
print(t.factor) // 0.5
print(
"size of MyThing:",
MemoryLayout.size(ofValue: MyThing())
) // 41 😱
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment