-
-
Save allevato/0bc901c05650fbd681fad11f2967ad8a to your computer and use it in GitHub Desktop.
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
@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