Guest User

Untitled

a guest
Jul 16th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.35 KB | None | 0 0
  1. //
  2. // UserDefaultsCodableExtension.swift
  3. // GradientTest
  4. //
  5. // Created by Ahmed Khattak on 16/07/2018.
  6. // Copyright © 2018 Ahmed Khattak. All rights reserved.
  7. //
  8.  
  9. import Foundation
  10.  
  11. extension UserDefaults {
  12.  
  13. func setCodable<Value: Codable>(codable: Value, forKey: String) {
  14.  
  15.  
  16.  
  17. if isSwiftCodableType(Value.self) || isFoundationCodableType(Value.self) {
  18. self.set(codable, forKey: forKey)
  19. return
  20. }
  21.  
  22. do {
  23. let encoder = JSONEncoder()
  24. let encoded = try encoder.encode(codable)
  25. self.set(encoded, forKey: forKey)
  26. self.synchronize()
  27. } catch {
  28. print(error)
  29. }
  30.  
  31. }
  32.  
  33.  
  34. func getCodable<Value: Codable>(ofType: Value.Type ,forKey: String) -> Value? {
  35.  
  36. if isSwiftCodableType(Value.self) || isFoundationCodableType(Value.self) {
  37. return self.value(forKey: forKey) as? Value
  38. }
  39.  
  40. guard let data = data(forKey: forKey) else {
  41. return nil
  42. }
  43.  
  44. do {
  45. let decoder = JSONDecoder()
  46. let decoded = try decoder.decode(Value.self, from: data)
  47. return decoded
  48. } catch {
  49. print(error)
  50. }
  51.  
  52. return nil
  53.  
  54. }
  55.  
  56.  
  57. func clearCodable(forKey: String) {
  58. self.set(nil, forKey: forKey)
  59. self.synchronize()
  60. }
  61.  
  62.  
  63. public func hasCodable(forKey: String) -> Bool {
  64. return self.value(forKey: forKey) != nil
  65. }
  66.  
  67.  
  68. /// Checks if the specified type is a Codable from the Swift standard library.
  69. ///
  70. /// - Parameter type: The type.
  71. /// - Returns: A boolean value.
  72. private func isSwiftCodableType<Value>(_ type: Value.Type) -> Bool {
  73. switch type {
  74. case is String.Type, is Bool.Type, is Int.Type, is Float.Type, is Double.Type:
  75. return true
  76. default:
  77. return false
  78. }
  79. }
  80.  
  81. /// Checks if the specified type is a Codable, from the Swift's core libraries
  82. /// Foundation framework.
  83. ///
  84. /// - Parameter type: The type.
  85. /// - Returns: A boolean value.
  86. private func isFoundationCodableType<Value>(_ type: Value.Type) -> Bool {
  87. switch type {
  88. case is Date.Type:
  89. return true
  90. default:
  91. return false
  92. }
  93. }
  94. }
Add Comment
Please, Sign In to add comment