Skip to content

Instantly share code, notes, and snippets.

@wleii
Created October 31, 2017 11:56
Show Gist options
  • Save wleii/e0c57f402049dc9a28df1c957ff2d72b to your computer and use it in GitHub Desktop.
Save wleii/e0c57f402049dc9a28df1c957ff2d72b to your computer and use it in GitHub Desktop.
Some thoughts about Swift Codable
public extension Decodable {
static func toModel(_ value: [String: Any], using decoder: JSONDecoder = JSONDecoder()) throws -> Self {
let data = try JSONSerialization.data(withJSONObject: value, options: JSONSerialization.WritingOptions.init(rawValue: 0))
return try toModel(data, using: decoder)
}
static func toModel(_ value: [[String: Any]], using decoder: JSONDecoder = JSONDecoder()) throws -> [Self] {
let data = try JSONSerialization.data(withJSONObject: value, options: JSONSerialization.WritingOptions.init(rawValue: 0))
return try toModel(data, using: decoder)
}
static func toModel(_ value: Data, using decoder: JSONDecoder = JSONDecoder()) throws -> Self {
return try decoder.decode(Self.self, from: value)
}
static func toModel(_ value: Data, using decoder: JSONDecoder = JSONDecoder()) throws -> [Self] {
return try decoder.decode([Self].self, from: value)
}
}
public extension Encodable {
/// must to use correct type
func toJSON() throws -> [String: Any] {
let data = try JSONEncoder().encode(self)
return try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as? [String: Any] ?? [:]
}
/// must to use correct type
func toJSONString() throws -> String {
let data = try JSONEncoder().encode(self)
return String.init(data: data, encoding: String.Encoding.utf8) ?? ""
}
}
public extension Encodable where Self: Sequence {
/// must to use correct type
func toJSON() throws -> [[String: Any]]? {
let data = try JSONEncoder().encode(self)
return try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as? [[String: Any]] ?? []
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment