Created
January 20, 2021 20:44
-
-
Save egzonpllana/35a1d4a635af75fb326d4fcca174553a to your computer and use it in GitHub Desktop.
Using TYUtils for Codable object through PropertyWrappers to store in User Preferences.
This file contains hidden or 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
import UIKit | |
import TYUtils | |
// Codable Model | |
struct Person: Codable { | |
var name: String | |
} | |
// UserDefault Extension | |
private extension UserDefault.Key { | |
static var personObject: Self { return "personObjectKey" } | |
} | |
class ViewController: UIViewController { | |
@CodableUserDefault(key: .personObject) | |
private var person: Person = Person(name: "Egzon Test - Not Updated!") | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
// Do any additional setup after loading the view, typically from a nib. | |
// For the tests | |
UserDefaults.standard.removeObject(forKey: UserDefault<Any>.Key.personObject.rawValue) | |
print("Initial default value", person) | |
person = Person(name: "Egzon Test - Updated!") | |
print("Full struct update", person) | |
person.name = "Egzon Test - Updated 2!" | |
print("Struct attribute update", person) | |
} | |
override func didReceiveMemoryWarning() { | |
super.didReceiveMemoryWarning() | |
// Dispose of any resources that can be recreated. | |
} | |
} | |
// CodableUserDefault.swift | |
@propertyWrapper | |
public class CodableUserDefault<T: Codable> { | |
fileprivate var internalValue: UserDefault<Data> | |
fileprivate let encoder: JSONEncoder = JSONEncoder() | |
fileprivate let decoder: JSONDecoder = JSONDecoder() | |
public var wrappedValue: T { | |
get { | |
do { | |
return try decoder.decode(T.self, from: internalValue.wrappedValue) | |
} catch { | |
fatalError(error.localizedDescription) | |
} | |
} | |
set { | |
do { | |
self.internalValue.wrappedValue = try encoder.encode(newValue) | |
} catch { | |
fatalError(error.localizedDescription) | |
} | |
} | |
} | |
public var projectedValue: String { internalValue.projectedValue } | |
public init(wrappedValue: T, key: UserDefault<Data>.Key, userDefault: UserDefaults = .standard) { | |
do { | |
let wrappedValueData = try encoder.encode(wrappedValue) | |
self.internalValue = .init(wrappedValue: wrappedValueData, key: key, userDefault: userDefault) | |
} catch { | |
fatalError(error.localizedDescription) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment