Skip to content

Instantly share code, notes, and snippets.

@amittkashyap
Last active March 28, 2020 14:02
Show Gist options
  • Save amittkashyap/c45ef80bfefab8a901e640f5e5bfedcf to your computer and use it in GitHub Desktop.
Save amittkashyap/c45ef80bfefab8a901e640f5e5bfedcf to your computer and use it in GitHub Desktop.
In this gist I will show you how to use custom keyDecodingStrategy/keyEncodingStrategy in new Codable/Decodable protocols in swift 4.1 with a simple example.
let json = """
[
{
"first-Name": "Taylor",
"last-Name": "swift",
"age": 28
},
{
"first-Name": "Tom",
"last-Name": "hanks",
"age": 61
}
]
"""
struct Person: Codable {
var firstName: String
var lastName: String
var age: Int
}
struct PersonKey: CodingKey {
var stringValue: String
var intValue: Int?
init?(stringValue: String) {
self.stringValue = stringValue
self.intValue = nil
}
init?(intValue: Int) {
self.stringValue = String(intValue)
self.intValue = intValue
}
}
let jsonDecoder = JSONDecoder()
//here you set the strategy, could be .convertFromSnakeCase apart from .useDefaultKeys. So basically we dont need the `CodingKeys enumerations` anymore
jsonDecoder.keyDecodingStrategy = .custom { keys -> CodingKey in
let key = keys.last!.stringValue.split(separator: "-").joined()
return PersonKey(stringValue: String(key))!
}
do {
let persons = try jsonDecoder.decode([Person].self, from: Data(json.utf8))
print(persons)
} catch {
print(error.localizedDescription)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment