UserDefaults.standard does not work correctly with String variables

0

How I'm having problems with a small code .. I am trying to save a String with UserDefaults.standard

private static let KEY : String = "KEY"
private static let NOMBRE : String = "Usuario"

let prefs = UserDefaults.standard
prefs.setValue(NOMBRE, forKey: KEY)

print(prefs.string(forKey: KEY)!)

and the result of my print is nil

And I only have problems with Strings Why can not I save a variable of type String ?

    
asked by marlonpya 07.02.2017 в 18:14
source

1 answer

1

The following code (which is the same as yours) works perfectly:

let userDefaults = UserDefaults.standard
userDefaults.setValue("Hola", forKey: "key")

print(userDefaults.string(forKey: "key"))

And what comes out through the console is:

  

Optional ("Hello")

On the other hand, you have to keep in mind that there is a known bug (but not documented) with the iOS 10 simulator. If you run the simulator from iOS 8/9 previous to iOS 10 for some reason it does not work correctly. One way to fix it is to restart the Mac and run only the iOS 10 simulator. Other users have had problems just because they have installed several simulators. If the problems persist, restart the simulator using Simulator - > Reset Content and Settings

    
answered by 07.02.2017 в 19:49