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
2
3
4
5
struct User: Codable {
var id: String
var name: String
var age: Int
}

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
2
3
4
5
6
7
8
9
10
11
let kUser = "kUser"

if let encoded = try? JSONEncoder().encode(user) {
UserDefaults.standard.set(encoded, forKey: "kUser")
}

if let userData = UserDefaults.standard.data(forKey: "kUser"),
let user = try? JSONDecoder().decode(User.self, from: userData) {

dump(user)
}

Now you can see the log on the console:

1
2
3
4
▿ __lldb_expr_10.User
- id: "ABCD1234"
- name: "Tim can Cook"
- age: 13

That’s it! You can download the final playground file here.