We have many ways to store and retrieve persistent data in iOS but let try to store a custom object into UserDefaults
with Codable
in Swift 4.
We have a custom object like this:
1 | struct User: Codable { |
And now, let define a object:
1 | let user = User(id: "abc123", name: "Tim can Cook", age: 13) |
Finally, we have to encode it using JSONEncoder
then it can be persist into UserDefaults.
1 | let kUser = "kUser" |
Now you can see the log on the console:
1 | ▿ __lldb_expr_10.User |
That’s it! You can download the final playground file here.