Skip to content

Instantly share code, notes, and snippets.

@gokselkoksal
Created February 12, 2019 10:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gokselkoksal/d94e559584de88a6ac786ec92ba07052 to your computer and use it in GitHub Desktop.
Save gokselkoksal/d94e559584de88a6ac786ec92ba07052 to your computer and use it in GitHub Desktop.
A placeholder decodable type
// 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