How to save struct into UserDefaults ?

NSUserDefaults, which is now called UserDefaults in Swift, is a mechanism for storing small pieces of data persistently across app launches. It’s typically used for storing user preferences, settings, and other simple data.

The reason why UserDefaults can only store class instances and not other types directly is due to its design. UserDefaults is primarily intended for storing property list types, which include basic data types such as strings, numbers, booleans, dates, arrays, and dictionaries. These types are automatically bridged to their Foundation equivalents (e.g., String to NSString, Int to NSNumber, etc.).

Class instances, when stored in UserDefaults, are archived into data representations using NSCoding, a protocol that allows objects to be encoded and decoded for storage and retrieval. By conforming to NSCoding, a class can provide methods to convert its properties to and from a binary data representation, allowing it to be stored in UserDefaults.

However, primitive types like structs or enums do not conform to NSCoding by default, so they cannot be stored directly in UserDefaults. If you want to store a struct or enum in UserDefaults, you would need to encode and decode it yourself into a property list compatible type (e.g., as an array or dictionary of primitive types) before storing it.

//--- Saving struct into Userdefaults --//

struct Person: Codable {
    var name: String
    var age: Int
}

let person = Person(name: "John", age: 30)

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

if let savedPersonData = UserDefaults.standard.data(forKey: "person"),
    let savedPerson = try? JSONDecoder().decode(Person.self, from: savedPersonData) {
    print(savedPerson) // This will print: Person(name: "John", age: 30)
}
// --In this example, the Person struct conforms to Codable, which implicitly conforms to NSCoding. We encode the person struct using JSONEncoder and store the resulting data in UserDefaults. Later, we decode the data back into a Person struct using JSONDecoder.---//

Leave a Comment

Your email address will not be published. Required fields are marked *