Created
July 20, 2021 11:11
-
-
Save cedricbahirwe/2e7e2cfb89e9010c79b6ae94b756f19d to your computer and use it in GitHub Desktop.
An implementation of Property Wrapper used to store data in UserDefaults in swift.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@propertyWrapper | |
struct LocalStorage<T: Codable> { | |
private let userDefaults: UserDefaults = .standard | |
private let key: String | |
private let defaultValue: T | |
init(wrappedValue defaultValue: T, key: String) { | |
self.key = key | |
self.defaultValue = defaultValue | |
} | |
var wrappedValue: T { | |
get { | |
guard let personInfo = userDefaults.object(forKey: key) as? Data else { | |
return defaultValue | |
} | |
return try! JSONDecoder().decode(T.self, from: personInfo) | |
} | |
set { | |
if let data = try? JSONEncoder().encode(newValue){ | |
userDefaults.set(data, forKey: key) | |
} else { | |
userDefaults.removeObject(forKey: key) | |
preconditionFailure("Can not encode the data") | |
} | |
} | |
} | |
} | |
extension LocalStorage where T: ExpressibleByNilLiteral { | |
init(key: String) { | |
self.init(wrappedValue: nil, key: key) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment