Created
February 12, 2019 10:45
-
-
Save gokselkoksal/d94e559584de88a6ac786ec92ba07052 to your computer and use it in GitHub Desktop.
A placeholder decodable type
This file contains 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
// Reference: https://github.com/asensei/AnyCodable/blob/master/Sources/AnyCodable/AnyCodable.swift | |
import Foundation | |
public struct AnyCodable { | |
// MARK: Initialization | |
public init(_ value: Any?) { | |
self.value = value | |
} | |
// MARK: Accessing Attributes | |
public let value: Any? | |
} | |
extension AnyCodable: Decodable { | |
public init(from decoder: Decoder) throws { | |
let container = try decoder.singleValueContainer() | |
if let value = try? container.decode(String.self) { | |
self.value = value | |
} else if let value = try? container.decode(Bool.self) { | |
self.value = NSNumber(value: value) | |
} else if container.decodeNil() { | |
self.value = nil | |
} else if let value = try? container.decode([String: AnyCodable].self) { | |
self.value = value.mapValues { $0.value } | |
} else if let value = try? container.decode([AnyCodable].self) { | |
self.value = value.map { $0.value } | |
} else if let value = try? container.decode(Int.self) { | |
self.value = NSNumber(value: value) | |
} else if let value = try? container.decode(Double.self) { | |
self.value = NSNumber(value: value) | |
} else { | |
throw DecodingError.dataCorruptedError( | |
in: container, | |
debugDescription: "Invalid value cannot be decoded" | |
) | |
} | |
} | |
} | |
extension AnyCodable: CustomStringConvertible { | |
public var description: String { | |
switch self.value { | |
case let value as CustomStringConvertible: | |
return value.description | |
default: | |
return String(describing: self.value) | |
} | |
} | |
} | |
extension AnyCodable: CustomDebugStringConvertible { | |
public var debugDescription: String { | |
switch self.value { | |
case let value as CustomDebugStringConvertible: | |
return value.debugDescription | |
default: | |
return self.description | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment