Skip to content

Instantly share code, notes, and snippets.

@d-date
Last active October 29, 2019 09:33
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save d-date/61e32fd662b1c0f5db8833c748543368 to your computer and use it in GitHub Desktop.
Save d-date/61e32fd662b1c0f5db8833c748543368 to your computer and use it in GitHub Desktop.
import Foundation
let intJson = #"{ "inUse": 1, "name": "Daiki Matsudate", "twitter": "d_date", "stars": 99999, "occupation": null}"#
let boolJson = #"{ "inUse": true, "name": "Daiki Matsudate", "twitter": "d_date", "stars": 99999, "occupation": null}"#
protocol Inherits {
associatedtype SuperType
var `super`: SuperType { get }
}
extension Inherits {
subscript<T>(dynamicMember keyPath: KeyPath<SuperType, T>) -> T {
return self.`super`[keyPath: keyPath]
}
}
@dynamicMemberLookup
struct A: Decodable, Inherits {
enum CodingKeys: String, CodingKey {
case inUse
}
let `super`: SuperA
let inUse: Bool
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.super = try .init(from: decoder)
self.inUse = {
if let boolValue = try? container.decode(Bool.self, forKey: .inUse) {
return boolValue
} else if let intValue = try? container.decode(Int.self, forKey: .inUse) {
return NSNumber(value: intValue).boolValue
}
fatalError()
}()
}
}
struct SuperA: Codable {
let name: String
let twitter: String
let stars: Int
let occupation: String?
}
let decoder = JSONDecoder()
let fromInt = try decoder.decode(A.self, from: intJson.data(using: .utf8)!)
let fromBool = try decoder.decode(A.self, from: boolJson.data(using: .utf8)!)
print("twitter", fromInt.twitter, separator: ": ")
print("occupation", fromInt.occupation ?? "無職", separator: ": ")
@d-date
Copy link
Author

d-date commented Oct 29, 2019

He raised issue about json decoding first:
https://twitter.com/shunkun_san/status/1189091946695757829?s=20

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment