Created
May 2, 2019 09:18
-
-
Save Przemyslaw-Wosko/c8366122bd935bd0c7a6700686a83ce3 to your computer and use it in GitHub Desktop.
Handy extension for Codable + transformers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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