JavascriptOptional.swift 893 B

123456789101112131415161718192021222324252627282930
  1. @propertyWrapper struct JavascriptOptional<T> {
  2. var wrappedValue: T?
  3. init(wrappedValue: T?) {
  4. self.wrappedValue = wrappedValue
  5. }
  6. }
  7. extension JavascriptOptional: Codable where T: Codable {
  8. init(from decoder: Decoder) throws {
  9. let container = try decoder.singleValueContainer()
  10. if let value = try? container.decode(T.self) {
  11. wrappedValue = value
  12. } else if (try? container.decode(Bool.self)) == false {
  13. wrappedValue = nil
  14. } else {
  15. throw DecodingError.dataCorruptedError(in: container, debugDescription: "Expected number or false")
  16. }
  17. }
  18. func encode(to encoder: Encoder) throws {
  19. var container = encoder.singleValueContainer()
  20. if let value = wrappedValue {
  21. try container.encode(value)
  22. } else {
  23. try container.encode(false)
  24. }
  25. }
  26. }