I am always getting nil when trying to assign any string to class level variable.
Below is my console output:
// 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")
}
}
}
When you call test
inside the setter, the getter is called to get the value of test
. At this point, the value for "test" is nil
inside UserDefaults. So instead of storing test
, you should using newValue
which is the value that you are about to set to the variable.
class Demo {
class var test: String? {
set {
UserDefaults.standard.set(newValue, forKey: "test")
print("test = \(test)")
}
get {
return UserDefaults.standard.string(forKey: "test")
}
}
}
From the docs,
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.
Check the ComputedProperties section in Properties to understand how getters and setters work.