Skip to content

Instantly share code, notes, and snippets.

@mateuszszklarek
Last active January 28, 2019 11:30
Show Gist options
  • Save mateuszszklarek/712e3766eaf14b8c557970afabbf61e5 to your computer and use it in GitHub Desktop.
Save mateuszszklarek/712e3766eaf14b8c557970afabbf61e5 to your computer and use it in GitHub Desktop.
enum Sex: String, Encodable {
case male
case female
case other
}
struct User: Encodable {
let id: Int
let name: String
let surname: String
let sex: Sex
private enum CodingKeys: String, CodingKey {
case id
case fullName = "full_name"
case sex
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(id, forKey: .id)
try container.encode(name + surname, forKey: .fullName)
try container.encode(sex, forKey: .sex)
}
}
let user = User(id: 19, name: "John", surname: "Doe", sex: .male)
let encodedUserData = try! JSONEncoder().encode(user)
let json = try JSONSerialization.jsonObject(with: encodedUserData)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment