Created
March 13, 2018 07:41
-
-
Save omochi/dec3e819ec7a485e33d43bcdd0c0d84a to your computer and use it in GitHub Desktop.
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
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