Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Be able to use own encoder and decoder. #1080

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 7 additions & 4 deletions Sources/CodableTransform.swift
Expand Up @@ -33,8 +33,13 @@ open class CodableTransform<T: Codable>: TransformType {

public typealias Object = T
public typealias JSON = Any

public init() {}
private let encoder: JSONEncoder
private let decoder: JSONDecoder

public init(decoder: JSONDecoder = .init(), encoder: JSONEncoder = .init()) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why you decided to create an initializer for these properties?

I think this development is unnecessary to use encoder and decoder because these properties aren't use anywhere except functions.

On the other hand some cases we don't need to create encoder or decoder.
For example; if data comes NULL in transformFromJSON (_ value:) -> Object? function returns immediately from guard statement and we don't create a decoder.

transformToJSON (_ value: ) -> JSON? has a same case, if value comes NULL we don't create encoder.

What do you think about this cases?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We want to set options for JSONDecoder and JSONEncoder.
For example, cannot set dataDecodingStrategy by current code.

self.encoder = encoder
self.decoder = decoder
}

open func transformFromJSON(_ value: Any?) -> Object? {
var _data: Data? = nil
Expand All @@ -49,7 +54,6 @@ open class CodableTransform<T: Codable>: TransformType {
guard let data = _data else { return nil }

do {
let decoder = JSONDecoder()
let item = try decoder.decode(T.self, from: data)
return item
} catch {
Expand All @@ -62,7 +66,6 @@ open class CodableTransform<T: Codable>: TransformType {
return nil
}
do {
let encoder = JSONEncoder()
let data = try encoder.encode(item)
let dictionary = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
return dictionary
Expand Down