Swift: 从磁盘缓存 int

Swift: Cache int from disk

对于用户设置的首选项,我有时不得不从磁盘读取值。为了避免不必要的(缓慢的)磁盘读取,我缓存了这些值,所以如果应用程序经常访问它们,它只会是内存访问,而不是存储访问。

这是我近十年来一直在做的事情的一个例子:

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
}

多年来我或多或少都在编写相同类型的算法,但在这一点上我确信一定有更聪明的方法来处理这个问题。

我考虑过编写一个小包装器,让我可以传递默认值和 UserDefaults 标识符,但我首先想确定 Swift 语言中是否已经包含类似的内容/如果有是 GitHub 上的一个小项目,或者如果我的方法在所有方面都是完全错误的——当然这取决于具体的用例,但通常这在性能方面对我来说效果很好

来自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.

所以,看来您不必担心“不必要的(缓慢的)磁盘读取”。