I would like to initialize a variable obj
by taking it from UserDefaults
, which returns a String?
, and if it's nil
build the value and assign it.
The following code works, but, at the end, my obj
is a String?
while I want it to be a String
(since it can't be nil
at this stage).
var obj = UserDefaults.standard.string(forKey: "my_key")// Here, obj is a String?
if obj == nil {
obj = ProcessInfo.processInfo.globallyUniqueString// Returns, a String
defaults.set(obj, forKey: "my_key")
defaults.synchronize()
}
// Here, obj is still a String?
Is there a good pattern / best practice for this kind of situation ?