For preferences set by users, I sometimes have to read values from disk. In order to avoid unnecessary (slow) disk reads, I cache these values so if the app accesses them often, it will only be memory access, not a storage access.
Here is an example for what I have been doing about this for almost a decade now:
let DEFAULT_COLUMN_COUNT = 4
var columnCount = -1
func getcolumnCount() -> Int {
if(columnCount != -1) {
return columnCount
} else if let count = UserDefaults.standard.object(forKey: "COLUMN_COUNT") as? Int {
columnCount = count
} else {
columnCount = DEFAULT_COLUMN_COUNT
}
return columnCount
}
I have been writing the same kind of algorithms more or less for years but at this point I'm sure there must be a smarter way to handle this.
I have thought about writing a small wrapper that lets me pass a default value and the UserDefaults identifier but I first wanted to make sure whether there is already something like this included in the Swift language/ if there is a small project for this on GitHub or if my approach is completely wrong in all regards - of course it depends on the specific use case but generally this has worked for me quite well in terms of performance
From Apple developer docs:
UserDefaults caches the information to avoid having to open the user’s defaults database each time you need a default value. When you set a default value, it’s changed synchronously within your process, and asynchronously to persistent storage and other processes.
So, it looks like you should not worry about "unnecessary (slow) disk reads".