Skip to content

Instantly share code, notes, and snippets.

@sukov
Created December 23, 2021 15:39
Show Gist options
  • Save sukov/44e67730615c76b1a3cc42a2ab43cd7c to your computer and use it in GitHub Desktop.
Save sukov/44e67730615c76b1a3cc42a2ab43cd7c to your computer and use it in GitHub Desktop.

Revisions

  1. sukov created this gist Dec 23, 2021.
    15 changes: 15 additions & 0 deletions UserDefaultsExtension.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,15 @@
    extension UserDefaults {
    /// Sets the codable value of the specified key.
    func set<Element: Codable>(_ value: Element, forKey key: String) {
    let data = try? JSONEncoder().encode(value)
    UserDefaults.standard.setValue(data, forKey: key)
    }

    /// Returns the codable value associated with the specified key.
    func codable<Element: Codable>(forKey key: String) -> Element? {
    guard let data = UserDefaults.standard.data(forKey: key) else { return nil }

    let element = try? JSONDecoder().decode(Element.self, from: data)
    return element
    }
    }