Skip to content

Commit

Permalink
feat: add user default + Codable support
Browse files Browse the repository at this point in the history
  • Loading branch information
gtokman committed May 3, 2021
1 parent 62373b9 commit 9def8e2
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions Sources/ExtensionKit/Foundation/UserDefaults.swift
@@ -0,0 +1,25 @@
import Foundation

public extension UserDefaults {

/// Get `Codable` model from user defaults
/// - Parameter key: String key
/// - Returns: Model
func getCodable<T: Codable>(forKey key: String) -> T? {
guard let data = UserDefaults.standard.data(forKey: key) else {
return nil
}
let element = try? JSONDecoder().decode(T.self, from: data)
return element
}

/// Set `Codable` mode to user defaults
/// - Parameters:
/// - value: Model
/// - key: String key
func setCodable<T: Codable>(value: T, forKey key: String) {
let data = try? JSONEncoder().encode(value)
UserDefaults.standard.setValue(data, forKey: key)
}

}

0 comments on commit 9def8e2

Please sign in to comment.