ios - 将变量与 UserDefaults 同步的正确方法

标签 ios swift swift3 userdefaults

我想在设置值时直接与 UserDefaults 保持变量同步。我是这样做的:

var userId: String {
    get {
        return UserDefaults.standard.string(forKey: kUserIdKey) ?? ""
    }
    set {
        UserDefaults.standard.set(newValue, forKey: kUserIdKey)
    }
}

它工作正常,但这样做是否正确?

如果是这样,Array 呢?

var tagsList: [Int] {
    get {
        return (UserDefaults.standard.object(forKey: kTagsList) as? [Int]) ?? [Int]()
    }
    set {
        UserDefaults.standard.set(newValue, forKey: kTagsList)
    }
}

如果我添加一个元素 tagsList.append(0),新值是否存储在 UserDefaults 中?

更新

这是我在 Playground 上拥有的东西: enter image description here

最佳答案

简短回答:是的。

长答案:数组和字符串是 Swift 中的 struct,它们在发生变异时语义上会生成一个全新的副本。

因此,setter 中的 newValue 是您对数组应用的任何变异的结果数组,无论它是 append 还是其他变异函数。

您可以像这样在 playground 中轻松验证此行为:

var array: [Int] {
    get { return [1, 2, 3] }
    set { print(newValue) }
}

array.append(4)
// Prints [1, 2, 3, 4]

关于ios - 将变量与 UserDefaults 同步的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46805344/

相关文章:

ios - Swift 3,使用带有闭包的函数扩展 Objective-C 泛型类

ios - Swift3 错误 : Type 'NSFastEnumerationIterator.Element' (aka 'Any' ) does not conform to protocol 'AnyObject'

ios - setStatusBarHidden :withAnimation doesn't cause subviews to auto-place correctly

ios - UIImagePickerController 编辑的图像在 iPad 中检索错误的图像

ios - CNMutableContact 和 iOS 13 中的 note 和 imageData

Swift 闭包 : Must Capture Lists Be Exhaustive?

swift3 - Nil 与预期的参数类型 Optional<UnsafeMutableRawPointer> 不兼容

ios - 如何检测 iPhone 5c 的颜色?

ios - Apple 会因为使用 cookie 而拒绝应用程序吗?

ios - 检测 SFSafariViewController 中的 URL 更改