Last active
October 29, 2019 09:33
-
-
Save d-date/61e32fd662b1c0f5db8833c748543368 to your computer and use it in GitHub Desktop.
Separate decoding process into normal and custom. See Also: https://github.com/vincent-pradeilles/swift-tips#implementing-pseudo-inheritance-between-structs
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 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: ": ") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
He raised issue about json decoding first:
https://twitter.com/shunkun_san/status/1189091946695757829?s=20