Sobes.tech
Junior

Tell me about encoding and decoding data in UserDefaults.

sobes.tech AI

Answer from AI

UserDefaults stores data in key-value pairs. For custom data types not directly supported (String, Int, Bool, Data, Array, Dictionary), encoding/decoding is required. The Codable protocol is used, which combines Encodable and Decodable.

Example of encoding a custom type:

struct User: Codable {
    let name: String
    let age: Int
}

let user = User(name: "Ivan", age: 30)

Using PropertyListEncoder and PropertyListDecoder, you can encode/decode Codable objects into Data for storage in UserDefaults.

Encoding:

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

Decoding:

if let savedData = UserDefaults.standard.data(forKey: "currentUser") {
    let decoder = PropertyListDecoder()
    if let loadedUser = try? decoder.decode(User.self, from: savedData) {
        print("Loaded user: \(loadedUser.name), age: \(loadedUser.age)")
    }
}

An alternative (less preferred for new projects) is using NSCoding with inheritance from NSObject.

Comparison of methods:

Method Protocol/Class Support for Value/Reference Types Required Methods Ease of Use
Codable Codable (Encodable, Decodable) Value & Reference Automatic synthesis when conditions are met High
NSCoding NSCoding Reference (requires NSObject) init(coder:), encode(with:) Medium

Codable is the modern and recommended approach due to its simplicity and automatic synthesis. NSCoding may be required for legacy code support.

Tell me about encoding and decoding data in… - sobes.tech