CodableArray.swift 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. //
  2. // CodableArray.swift
  3. // Todos
  4. //
  5. // Created by Sam Jaffe on 3/1/26.
  6. //
  7. import Foundation
  8. import SwiftData
  9. internal import Combine
  10. typealias CodableArray<A: Codable> = [A]
  11. // swiftlint:disable line_length
  12. /**
  13. * @brief Provides a UserDefaults-compatibiliy layer for Array<URLHint> that
  14. * allows seamless reading/writing on program startup and changes.
  15. * We bind this type to its JSON-String representation rather than, say, an
  16. * Array of dictionaries because @AppStorage only operates on scalar types.
  17. *
  18. * @author Sam Jaffe
  19. * @author KD Knowledge Diet https://paigeshin1991.medium.com/saving-custom-codable-types-in-appstorage-or-scenestorage-in-swiftui-0073032f3f94
  20. *
  21. * The \@retroactive guards against the Swift developers changing Array<T> to
  22. * comply w/ RawRepresentable in the future
  23. */
  24. extension CodableArray: @retroactive RawRepresentable {
  25. // swiftlint:enable line_length
  26. public init?(rawValue: String) {
  27. guard let data = rawValue.data(using: .utf8),
  28. let result = try? JSONDecoder().decode(CodableArray.self, from: data)
  29. else {
  30. return nil
  31. }
  32. self = result
  33. }
  34. public var rawValue: String {
  35. guard let data = try? JSONEncoder().encode(self),
  36. let result = String(data: data, encoding: .utf8)
  37. else {
  38. return "[]"
  39. }
  40. return result
  41. }
  42. }