Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // UserDefaultsCodableExtension.swift
- // GradientTest
- //
- // Created by Ahmed Khattak on 16/07/2018.
- // Copyright © 2018 Ahmed Khattak. All rights reserved.
- //
- import Foundation
- extension UserDefaults {
- func setCodable<Value: Codable>(codable: Value, forKey: String) {
- if isSwiftCodableType(Value.self) || isFoundationCodableType(Value.self) {
- self.set(codable, forKey: forKey)
- return
- }
- do {
- let encoder = JSONEncoder()
- let encoded = try encoder.encode(codable)
- self.set(encoded, forKey: forKey)
- self.synchronize()
- } catch {
- print(error)
- }
- }
- func getCodable<Value: Codable>(ofType: Value.Type ,forKey: String) -> Value? {
- if isSwiftCodableType(Value.self) || isFoundationCodableType(Value.self) {
- return self.value(forKey: forKey) as? Value
- }
- guard let data = data(forKey: forKey) else {
- return nil
- }
- do {
- let decoder = JSONDecoder()
- let decoded = try decoder.decode(Value.self, from: data)
- return decoded
- } catch {
- print(error)
- }
- return nil
- }
- func clearCodable(forKey: String) {
- self.set(nil, forKey: forKey)
- self.synchronize()
- }
- public func hasCodable(forKey: String) -> Bool {
- return self.value(forKey: forKey) != nil
- }
- /// Checks if the specified type is a Codable from the Swift standard library.
- ///
- /// - Parameter type: The type.
- /// - Returns: A boolean value.
- private func isSwiftCodableType<Value>(_ type: Value.Type) -> Bool {
- switch type {
- case is String.Type, is Bool.Type, is Int.Type, is Float.Type, is Double.Type:
- return true
- default:
- return false
- }
- }
- /// Checks if the specified type is a Codable, from the Swift's core libraries
- /// Foundation framework.
- ///
- /// - Parameter type: The type.
- /// - Returns: A boolean value.
- private func isFoundationCodableType<Value>(_ type: Value.Type) -> Bool {
- switch type {
- case is Date.Type:
- return true
- default:
- return false
- }
- }
- }
Add Comment
Please, Sign In to add comment