Skip to content

Commit

Permalink
UserDefaults for codable type
Browse files Browse the repository at this point in the history
  • Loading branch information
rafaelesantos committed Sep 20, 2024
1 parent 2fca2db commit 4f4e035
Showing 1 changed file with 8 additions and 6 deletions.
14 changes: 8 additions & 6 deletions Sources/RefdsShared/Data/RefdsDefaults.swift
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import Foundation

@propertyWrapper
public struct RefdsDefaults<Value> {
public struct RefdsDefaults<Value: Codable> {
let key: String
var defaultValue: Value? = nil

Expand All @@ -14,19 +14,21 @@ public struct RefdsDefaults<Value> {
}

public var wrappedValue: Value? {
get { Self.defaults.object(forKey: key) as? Value }
set { Self.defaults.set(newValue, forKey: key) }
get { Self.get(for: key) }
set { Self.set(newValue, for: key) }
}

static var defaults: UserDefaults {
UserDefaults(suiteName: "refds.defaults") ?? .standard
}

public static func get(for key: String) -> Value? {
defaults.object(forKey: key) as? Value
guard let data = defaults.data(forKey: key) else { return nil }
return try? JSONDecoder().decode(Value.self, from: data)
}

public static func set(_ value: Value, for key: String) {
defaults.set(value, forKey: key)
public static func set(_ value: Value?, for key: String) {
guard let data = value.asData else { return }
defaults.set(data, forKey: key)
}
}

0 comments on commit 4f4e035

Please sign in to comment.