Created
June 15, 2018 10:57
-
-
Save onmyway133/705dc3834e5cbb66464818eb207828b9 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
public class TransformerFactory { | |
public static func forData() -> Transformer<Data> { | |
let toData: (Data) throws -> Data = { $0 } | |
let fromData: (Data) throws -> Data = { $0 } | |
return Transformer<Data>(toData: toData, fromData: fromData) | |
} | |
public static func forImage() -> Transformer<Image> { | |
let toData: (Image) throws -> Data = { image in | |
return try image.cache_toData().unwrapOrThrow(error: StorageError.transformerFail) | |
} | |
let fromData: (Data) throws -> Image = { data in | |
return try Image(data: data).unwrapOrThrow(error: StorageError.transformerFail) | |
} | |
return Transformer<Image>(toData: toData, fromData: fromData) | |
} | |
public static func forCodable<U: Codable>(ofType: U.Type) -> Transformer<U> { | |
let toData: (U) throws -> Data = { object in | |
let wrapper = TypeWrapper<U>(object: object) | |
let encoder = JSONEncoder() | |
return try encoder.encode(wrapper) | |
} | |
let fromData: (Data) throws -> U = { data in | |
let decoder = JSONDecoder() | |
return try decoder.decode(TypeWrapper<U>.self, from: data).object | |
} | |
return Transformer<U>(toData: toData, fromData: fromData) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment