Skip to content

Instantly share code, notes, and snippets.

@philipyoungg
Created December 16, 2020 21:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save philipyoungg/8c67eafef7967e4d34c58c3890482f0f to your computer and use it in GitHub Desktop.
Save philipyoungg/8c67eafef7967e4d34c58c3890482f0f to your computer and use it in GitHub Desktop.
Decodable enumeration
import UIKit
protocol VercelPayload {
var name: String {get}
var id: String {get}
}
struct GitBucket: VercelPayload, Codable {
var name: String
var id: String
var bucket: String
}
struct Github: VercelPayload, Codable {
var name: String
var id: String
var hub: String
}
enum Vercel: Decodable {
case gitbucket(GitBucket)
case github(Github)
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let github = try? container.decode(Github.self) {
self = .github(github)
} else if let gitbucket = try? container.decode(GitBucket.self) {
self = .gitbucket(gitbucket)
} else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "Does not conform to anything")
}
}
}
let mockJSON = Data()
do {
let globalDecoder = JSONDecoder()
let decoded = try globalDecoder.decode(Vercel.self, from: mockJSON)
switch decoded {
case .github(let decodedHub):
print(decodedHub.name, decodedHub.hub)
case .gitbucket(let decodedBucket):
print(decodedBucket.name, decodedBucket.bucket)
}
} catch {
print("doesn't conform to payload")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment