UserDefaults swift 5 code example

Example 1: save date to userdefaults swift

//save as Date
UserDefaults.standard.set(Date(), forKey: key)

//read
let date = UserDefaults.standard.object(forKey: key) as! Date
let df = DateFormatter()
df.dateFormat = "dd/MM/yyyy HH:mm"
print(df.string(from: date))

Example 2: how to fmake sure that data is save in userdefault

let name = "John Doe"
UserDefaults.standard.set(name, forKey: "name")

Example 3: how to fmake sure that data is save in userdefault

if let appDomain = Bundle.main.bundleIdentifier {
UserDefaults.standard.removePersistentDomain(forName: appDomain)
 }

Tags:

Misc Example