Created
December 16, 2020 21:04
-
-
Save philipyoungg/8c67eafef7967e4d34c58c3890482f0f to your computer and use it in GitHub Desktop.
Decodable enumeration
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
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