Created
August 15, 2019 20:09
-
-
Save mortenbekditlevsen/bd2588fc5935da3a9cf8f084ea97bfab to your computer and use it in GitHub Desktop.
Lazy resolver
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
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