I have an enum like this:
enum Environment {
case Production
case Staging
case Dev
}
And I\'d like to save an instance in NSUserDef
Codable
protocolExtent Environment
enum that conforms to Codable
protocol to encode and decode values as Data
.
enum Environment: String, Codable {
case Production
case Staging
case Dev
}
A wrapper for UserDefaults
:
struct UserDefaultsManager {
static var userDefaults: UserDefaults = .standard
static func set(_ value: T, forKey: String) where T: Encodable {
if let encoded = try? JSONEncoder().encode(value) {
userDefaults.set(encoded, forKey: forKey)
}
}
static func get(forKey: String) -> T? where T: Decodable {
guard let data = userDefaults.value(forKey: forKey) as? Data,
let decodedData = try? JSONDecoder().decode(T.self, from: data)
else { return nil }
return decodedData
}
}
// Set
let environment: Environment = .Production
UserDefaultsManager.set(environment, forKey: "environment")
// Get
let environment: Environment? = UserDefaultsManager.get(forKey: "environment")