Created
January 14, 2020 20:56
-
-
Save ystrohanov/cc3086fd6fe2315231e0efda8dc9968c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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