Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- func customCodableEnum() {
- struct SubJSON: Codable {
- let subJSONKey: String
- }
- enum MyEnum<T: Codable>: Codable {
- case myCase(key: String, value: T)
- case otherCase(Int)
- case unmanagedCase //Could throw a custom error instead
- init(from decoder: Decoder) throws {
- let values = try decoder.singleValueContainer()
- if let asInt = try? values.decode(Int.self) {
- self = .otherCase(asInt)
- } else {
- let asDict = try values.decode([String: T].self)
- if let first = asDict.keys.first {
- self = .myCase(key: first, value: asDict[first]!)
- } else {
- self = .unmanagedCase //Could throw a custom error instead
- }
- }
- }
- }
- do {
- let jsonStr = """
- [3,
- {"Key": {
- "subJSONKey": "SubJSONValue"
- }
- }
- ]
- """
- let json = Data(jsonStr.utf8)
- let enums = try JSONDecoder().decode([MyEnum<SubJSON>].self, from: json)
- enums.forEach {
- switch $0 {
- case .myCase(key: let key, value: let value):
- print("MyEnum.myCase(key: \(key), value: \(value))")
- case .otherCase(let intValue):
- print("MyEnum.otherCase(\(intValue))")
- case .unmanagedCase:
- print("MyEnum.unmanagedCase")
- }
- }
- } catch {
- print("Error: \(error)")
- }
- }
- customCodableEnum()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement