Skip to content

Instantly share code, notes, and snippets.

@mortenbekditlevsen
Created August 15, 2019 20:09
Show Gist options
  • Save mortenbekditlevsen/bd2588fc5935da3a9cf8f084ea97bfab to your computer and use it in GitHub Desktop.
Save mortenbekditlevsen/bd2588fc5935da3a9cf8f084ea97bfab to your computer and use it in GitHub Desktop.
Lazy resolver
class TestResolver {
var identifier: String
@ResolveKeypathLazily(keyPath: \TestResolver.identifier)
var hamster: Int = 1
init(identifier: String) {
self.identifier = identifier
}
}
@propertyWrapper
struct ResolveKeypathLazily<Value: Equatable, T> {
private var stored: Value
private let aKeyPath: KeyPath<T, String>
private var resolved: String?
public init(wrappedValue: Value, keyPath: KeyPath<T, String>) {
self.stored = wrappedValue
self.aKeyPath = keyPath
}
var wrappedValue: Value {
get { fatalError() }
set { fatalError() }
}
public static subscript(
_enclosingInstance observed: T,
wrapped wrappedKeyPath: ReferenceWritableKeyPath<T, Value>,
storage storageKeyPath: ReferenceWritableKeyPath<T, Self>
) -> Value {
get {
// Resolve the keypath
if observed[keyPath: storageKeyPath].resolved == nil {
let keyPath = observed[keyPath: storageKeyPath].aKeyPath
observed[keyPath: storageKeyPath].resolved = observed[keyPath: keyPath]
}
return observed[keyPath: storageKeyPath].stored
}
set {
observed[keyPath: storageKeyPath].stored = newValue
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment