-
-
Notifications
You must be signed in to change notification settings - Fork 46
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Adding a layer of caching to skip JSON decoding when accessing a Stor…
…edValue
- Loading branch information
Showing
3 changed files
with
34 additions
and
2 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
import Foundation | ||
|
||
/// `CachedValue` exists internally for the purpose of creating a reference value, preventing the need | ||
/// to create a `JSONDecoder` and invoke a decode step every time we need to access a `StoredValue` externally. | ||
internal final class CachedValue<Item: Codable> { | ||
private var cachedValue: Item? | ||
public var retrieveValue: () -> Item | ||
|
||
init(retrieveValue: @escaping () -> Item) { | ||
self.retrieveValue = retrieveValue | ||
self.cachedValue = self.retrieveValue() | ||
} | ||
|
||
func set(_ value: Item) { | ||
self.cachedValue = value | ||
} | ||
|
||
var wrappedValue: Item? { | ||
if let cachedValue { | ||
cachedValue | ||
} else { | ||
self.retrieveValue() | ||
} | ||
} | ||
} |
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
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