07-21-2023, 10:18 PM
> Swift 5: The **Codable** protocol can be used instead of **NSKeyedArchiever**.
struct User: Codable {
let id: String
let mail: String
let fullName: String
}
The **Pref** struct is custom wrapper around the UserDefaults standard object.
struct Pref {
static let keyUser = "Pref.User"
static var user: User? {
get {
if let data = UserDefaults.standard.object(forKey: keyUser) as? Data {
do {
return try JSONDecoder().decode(User.self, from: data)
} catch {
print("Error while decoding user data")
}
}
return nil
}
set {
if let newValue = newValue {
do {
let data = try JSONEncoder().encode(newValue)
UserDefaults.standard.set(data, forKey: keyUser)
} catch {
print("Error while encoding user data")
}
} else {
UserDefaults.standard.removeObject(forKey: keyUser)
}
}
}
}
So you can use it this way:
Pref.user?.name = "John"
if let user = Pref.user {...
struct User: Codable {
let id: String
let mail: String
let fullName: String
}
The **Pref** struct is custom wrapper around the UserDefaults standard object.
struct Pref {
static let keyUser = "Pref.User"
static var user: User? {
get {
if let data = UserDefaults.standard.object(forKey: keyUser) as? Data {
do {
return try JSONDecoder().decode(User.self, from: data)
} catch {
print("Error while decoding user data")
}
}
return nil
}
set {
if let newValue = newValue {
do {
let data = try JSONEncoder().encode(newValue)
UserDefaults.standard.set(data, forKey: keyUser)
} catch {
print("Error while encoding user data")
}
} else {
UserDefaults.standard.removeObject(forKey: keyUser)
}
}
}
}
So you can use it this way:
Pref.user?.name = "John"
if let user = Pref.user {...