Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
import Foundation
import UIKit
let json = """
"first_name": "Shakti",
"last_name": "prakash",
"first_name": "Soumen",
"last_name": "Mohanty",
let jsonData = Data(json.utf8)
enum VariacType:Codable{
func encode(to encoder: Encoder) throws {
case int(Int)
case string(String)
init(from decoder: Decoder) throws {
if let intValue = try? decoder.singleValueContainer().decode(Int.self) {
self = .int(intValue)
if let stringValue = try? decoder.singleValueContainer().decode(String.self){
self = .string(stringValue)
throw VariacError.missingValue
enum VariacError: Error {
case missingValue
extension VariacType {
var Value:String {
switch self {
case .int(let intvalue):
return String(intvalue)
case .string(let stringValue):
return stringValue
struct Person: Codable{
var firstName: String
var lastName: String
var age: VariacType
var address: String
private enum CodingKeys: String, CodingKey{
case firstName = "first_name"
case lastName = "last_name"
case age
case address
func encode(to Encoder: Encoder) throws{
init(from decoder: Decoder) throws{
let container = try decoder.container(keyedBy: CodingKeys.self)
firstName = try container.decode(String.self, forKey: .firstName)
lastName = try container.decode(String.self, forKey: .lastName)
// age = try container.decode(VariacType.self, forKey: .age)
age = (try container.decodeIfPresent(VariacType.self, forKey: .age)) ??
address =
(try container.decodeIfPresent(String.self, forKey: .address)) ?? "Unknown Address"
let decoder = JSONDecoder()
do {
let response = try decoder.decode([Person].self, from: jsonData)
} catch let error {
print("Parsing Failed \(error.localizedDescription)")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment