Skip to content

Instantly share code, notes, and snippets.

@Ravi61
Created July 13, 2017 12:27
Show Gist options
  • Select an option

  • Save Ravi61/d5a89801ec73c9be763a90f5233c906d to your computer and use it in GitHub Desktop.

Select an option

Save Ravi61/d5a89801ec73c9be763a90f5233c906d to your computer and use it in GitHub Desktop.
Custom Encoding Code
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