Skip to content

Instantly share code, notes, and snippets.

@olivaresf
Created October 5, 2020 04:08
Show Gist options
  • Save olivaresf/9ac5110357f6add3403bdadbb0cc6098 to your computer and use it in GitHub Desktop.
Save olivaresf/9ac5110357f6add3403bdadbb0cc6098 to your computer and use it in GitHub Desktop.
#warning("Documentation needs work.")
#warning("Who is calling `storedData`? Why is it private?")
/// What data?
/// - The cache, if available.
/// - If the cache is not available, try from UserDefaults
/// - If UserDefaults doesn't have any data, then return `defaultStoreData`
///
/// - Returns: a Store Data object?
private var storedData: StoredData {
// Do we have a cache?
guard let cache = storedDataCache else {
// We do not. Do we have the previous data in UserDefaults?
guard let savedJSONData = UserDefaults.standard.value(forKey: key) as? Data else {
// We don't have previous data.
// Generate it.
print("No data found for key \(key), generating default values")
storedDataCache = defaultStoreData
#warning("We should save this to UserDefaults.")
return storedDataCache!
}
// We do have the previous data in UserDefaults.
// Transform it into a JSON.
var storedData = defaultStoreData
do {
storedData = try JSONDecoder().decode(StoredData.self, from: savedJSONData)
} catch {
print("error reading stored data \(error), generating default values")
}
storedDataCache = storedData
return storedData
}
return cache
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment