尝试将任何字符串分配给类级别变量时,我总是得到 nil。
下面是我的控制台输出:
// test = nil
// Demo.test = nil
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
Demo.test = "app"
print("Demo.test = \(Demo.test)")
}
}
class Demo {
class var test: String? {
set {
UserDefaults.standard.set(test, forKey: "test")
print("test = \(test)")
}
get {
return UserDefaults.standard.string(forKey: "test")
}
}
}
最佳答案
当您在 setter 中调用 test
时,将调用 getter 以获取 test
的值。此时,“test”的值在 UserDefaults 中为 nil
。因此,您不应存储 test
,而应使用 newValue
,这是您要设置给变量的值。
class Demo {
class var test: String? {
set {
UserDefaults.standard.set(newValue, forKey: "test")
print("test = \(test)")
}
get {
return UserDefaults.standard.string(forKey: "test")
}
}
}
来自文档,
If a computed property’s setter does not define a name for the new value to be set, a default name of
newValue
is used.
检查 Properties 中的 ComputedProperties 部分了解 getter 和 setter 的工作原理。
关于ios - 类级别变量设置为什么总是为零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53441985/