Created
July 13, 2017 12:27
-
-
Save Ravi61/d5a89801ec73c9be763a90f5233c906d to your computer and use it in GitHub Desktop.
Custom Encoding Code
This file contains hidden or 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
| struct BattleShip { | |
| var name: String | |
| var created: String | |
| var movieName: String | |
| var director: String | |
| enum CodingKeys: String, CodingKey { | |
| case name | |
| case created | |
| case film | |
| } | |
| enum FilmInfoKeys: String, CodingKey { | |
| case name | |
| case director | |
| } | |
| } | |
| extension BattleShip: Encodable, Decodable { | |
| init(from decoder: Decoder) throws { | |
| let values = try decoder.container(keyedBy: CodingKeys.self) | |
| name = try values.decodeIfPresent(String.self, forKey: .name) ?? "" | |
| created = try values.decodeIfPresent(String.self, forKey: .created) ?? "" | |
| let filmInfo = try values.nestedContainer(keyedBy: FilmInfoKeys.self, forKey: .film) | |
| movieName = try filmInfo.decodeIfPresent(String.self, forKey: .name) ?? "" | |
| director = try filmInfo.decodeIfPresent(String.self, forKey: .director) ?? "" | |
| } | |
| func encode(to encoder: Encoder) throws { | |
| var container = encoder.container(keyedBy: CodingKeys.self) | |
| try container.encode(name, forKey: .name) | |
| try container.encode(created, forKey: .created) | |
| var filmInfo = container.nestedContainer(keyedBy: FilmInfoKeys.self, forKey: .film) | |
| try filmInfo.encode(movieName, forKey: .name) | |
| try filmInfo.encode(director, forKey: .director) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment