Skip to content

Instantly share code, notes, and snippets.

@ystrohanov
Created January 14, 2020 20:56
Show Gist options
  • Save ystrohanov/cc3086fd6fe2315231e0efda8dc9968c to your computer and use it in GitHub Desktop.
Save ystrohanov/cc3086fd6fe2315231e0efda8dc9968c to your computer and use it in GitHub Desktop.
//
// ListItem.swift
// FetchRewardsAssignment
//
// Created by Strohanov, Yevhen (Chicago) on 1/14/20.
// Copyright © 2020 Organization. All rights reserved.
//
import Foundation
class ListItem: Decodable {
var id: Int?
var listId: Int?
var name: String? {
if let string = _name?.string {
return string
} else if let integer = _name?.int {
return String(describing: integer)
}
return nil
}
var _name: JSONValue?
enum CodingKeys: String, CodingKey {
case id = "id"
case listId = "listId"
case _name = "name"
}
// required init(from decoder: Decoder) {
// }
}
enum JSONValue: Decodable {
case int(Int)
case string(String)
init(from decoder: Decoder) throws {
let singleValueContainer = try decoder.singleValueContainer()
if let value = try? singleValueContainer.decode(Int.self) {
self = .int(value)
return
} else if let value = try? singleValueContainer.decode(String.self) {
self = .string(value)
return
}
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Could not find reasonable type to map to JSONValue"))
}
}
extension JSONValue {
public var string: String? {
switch self {
case .string(let value):
return value
default:
return nil
}
}
public var int: Int? {
switch self {
case .int(let value):
return value
default:
return nil
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment