Skip to content

Instantly share code, notes, and snippets.

@mackoj
Last active October 19, 2022 21:15
Show Gist options
  • Save mackoj/88797cb1ef4ace05af1b84394374d49f to your computer and use it in GitHub Desktop.
Save mackoj/88797cb1ef4ace05af1b84394374d49f to your computer and use it in GitHub Desktop.
This add the ability to use URL when decoding JSON directly in the model
import Foundation
// public struct Model: Codable {
// public let test: URL?
// public let test2: URL
// ...
// }
// ⚠️ This is not a universal solution tho in orfer to handle properlu fileURL URL should be init with `URL(fileURLWithPath:)` instead of URL(string:)
extension KeyedDecodingContainer {
public func decode(_ type: URL.Type, forKey key: KeyedDecodingContainer<K>.Key) throws -> URL {
let decodedValue = try self.decode(String.self, forKey: key)
if let url = URL(string: decodedValue) {
return url
}
throw(DecodingError.typeMismatch(URL.self, DecodingError.Context(codingPath: [key], debugDescription: "Failed to transform the underling string(\(decodedValue)) into URL")))
}
public func decodeIfPresent(_ type: URL.Type, forKey key: KeyedDecodingContainer<K>.Key) throws -> URL? {
if let decodedValue = try self.decodeIfPresent(String.self, forKey: key), let url = URL(string: decodedValue) {
return url
}
return nil
}
}
extension KeyedEncodingContainer {
public mutating func encode(_ value: URL, forKey key: KeyedEncodingContainer<K>.Key) throws {
try self.encode(value.absoluteString, forKey: key)
}
public mutating func encodeIfPresent(_ value: URL?, forKey key: KeyedEncodingContainer<K>.Key) throws {
try self.encodeIfPresent(value?.absoluteString, forKey: key)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment