Skip to content

Instantly share code, notes, and snippets.

@Przemyslaw-Wosko
Created May 2, 2019 09:18
Show Gist options
  • Save Przemyslaw-Wosko/c8366122bd935bd0c7a6700686a83ce3 to your computer and use it in GitHub Desktop.
Save Przemyslaw-Wosko/c8366122bd935bd0c7a6700686a83ce3 to your computer and use it in GitHub Desktop.
Handy extension for Codable + transformers
import Foundation
protocol TransformerType {
associatedtype Object
associatedtype JSON
func transformFromJSON(_ value: Any) throws -> Object
func transformToJSON(_ value: Object) throws -> JSON
}
extension KeyedDecodingContainer {
func decode<T: Decodable>(_ key: K) throws -> T {
return try decode(T.self, forKey: key)
}
func decodeIfPresent<T: Decodable>(_ key: K) throws -> T? {
return try decodeIfPresent(T.self, forKey: key)
}
func decode<T: Decodable, Transform: TransformerType>(_ key: K, transformer: Transform) throws -> T where Transform.Object == T, Transform.JSON: Decodable {
let decodedValue = try decode(Transform.JSON.self, forKey: key)
let transformedValue = try transformer.transformFromJSON(decodedValue)
return transformedValue
}
func decodeIfPresent<T: Decodable, Transform: TransformerType>(_ key: K, transformer: Transform) throws -> T? where Transform.Object == T, Transform.JSON: Decodable {
guard let decodedValue = try decodeIfPresent(Transform.JSON.self, forKey: key) else { return nil }
let transformedValue = try transformer.transformFromJSON(decodedValue)
return transformedValue
}
}
extension KeyedEncodingContainer {
mutating func encode<Value, Transformer: TransformerType>(_ value: Value, forKey: K, transformer: Transformer) throws where Value == Transformer.Object, Transformer.JSON: Encodable {
let transformedValue = try transformer.transformToJSON(value)
try self.encode(transformedValue, forKey: forKey)
}
mutating func encode<Value, Transformer: TransformerType>(_ value: Value?, forKey: K, transformer: Transformer) throws where Value == Transformer.Object, Transformer.JSON: Encodable {
guard let value = value else { return }
let transformedValue = try transformer.transformToJSON(value)
try self.encode(transformedValue, forKey: forKey)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment