Skip to content

Instantly share code, notes, and snippets.

@omochi
Created March 13, 2018 07:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save omochi/dec3e819ec7a485e33d43bcdd0c0d84a to your computer and use it in GitHub Desktop.
Save omochi/dec3e819ec7a485e33d43bcdd0c0d84a to your computer and use it in GitHub Desktop.
public protocol CodableByInnerJSONType : Codable {
associatedtype JSON: Codable
init(fromInnerJSON json: JSON)
func encodeToInnerJSON() -> JSON
}
extension CodableByInnerJSONType {
public init(from decoder: Decoder) throws {
let json = try JSON(from: decoder)
self.init(fromInnerJSON: json)
}
public func encode(to encoder: Encoder) throws {
let json = encodeToInnerJSON()
try json.encode(to: encoder)
}
}
// example
public struct UserCredential : CodableByInnerJSONType {
public struct JSON : Codable {
public var id: Int
public var password: String
}
public init(fromInnerJSON json: JSON) {
self.id = json.id
self.password = json.password
}
public var id: Int
public var password: String
public func encodeToInnerJSON() -> JSON {
return JSON(id: id,
password: password)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment