Skip to content

Instantly share code, notes, and snippets.

@donnywals
Created January 2, 2021 18:01
Show Gist options
  • Save donnywals/1dc84bc8d9aaae88afeb8b2e247a9f58 to your computer and use it in GitHub Desktop.
Save donnywals/1dc84bc8d9aaae88afeb8b2e247a9f58 to your computer and use it in GitHub Desktop.
import Foundation
let json = """
{
"userId": 0,
"name": "Donny"
}
""".data(using: .utf8)!
let fakeSQLite = """
{
"user_id": 0,
"name": "Donny"
}
""".data(using: .utf8)!
struct User: Decodable {
enum JSONDecodingKeys: CodingKey {
case userId, name
}
enum SQLiteDecodingKeys: String, CodingKey {
case userId = "user_id"
case name
}
let userId: Int
let name: String
init(from decoder: Decoder) throws {
if let origin = decoder.userInfo[.sqliteOrigin] as? Bool, origin == true {
let container = try decoder.container(keyedBy: SQLiteDecodingKeys.self)
self.userId = try container.decode(Int.self, forKey: .userId)
self.name = try container.decode(String.self, forKey: .name)
} else {
let container = try decoder.container(keyedBy: JSONDecodingKeys.self)
self.userId = try container.decode(Int.self, forKey: .userId)
self.name = try container.decode(String.self, forKey: .name)
}
}
}
extension CodingUserInfoKey {
static let sqliteOrigin = CodingUserInfoKey(rawValue: "sqliteOrigin")!
static let jsonOrigin = CodingUserInfoKey(rawValue: "jsonOrigin")!
}
let sqliteDecoder = JSONDecoder()
sqliteDecoder.userInfo[.sqliteOrigin] = true
let user1 = try! sqliteDecoder.decode(User.self, from: fakeSQLite)
let jsonDecoder = JSONDecoder()
sqliteDecoder.userInfo[.jsonOrigin] = true
let user2 = try! jsonDecoder.decode(User.self, from: json)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment