Greetings, traveler!
Imagine a situation where you want to discuss the backend API with your colleagues. You suggest improving the existing server response and wish to demonstrate it. However, your colleagues expect you to send them a JSON example. What could be simpler? Create the desired model in Swift, encode it using JSONEncoder, and print the result.
Your model has a dictionary that uses an enumeration as a key and an array of strings as values. You have created something like this.
enum EmotionIconKind: String, Encodable {
case emoticons
case emoji
}
struct ServerResponce: Encodable {
let emotionIconDictionary: [EmotionIconKind: [String]] = [
.emoticons: [":)", ":3", ":D"],
.emoji: ["😊", "😸", "😄"]
]
}
We encoded the model and printed the result to the console.
let jsonData = try JSONEncoder().encode(ServerResponce())
print(String(decoding: jsonData, as: UTF8.self))
The result could look more convenient; it’s just a scattered array of elements. And this is different from what you wanted to show your colleagues.
{
"emotionIconDictionary":[
"emoji",
[
"😊",
"😸",
"😄"
],
"emoticons",
[
":)",
":3",
":D"
]
]
}
Starting with Swift 5.6, this problem is solved very simply. It is enough to add conformance with the CodingKeyRepresentable protocol for your enumeration.
enum EmotionIconKind: String, Encodable, CodingKeyRepresentable {
case emoticons
case emoji
}
Done! Now, your JSON model indeed resembles a dictionary.
{
"emotionIconDictionary":{
"emoticons":[
":)",
":3",
":D"
],
"emoji":[
"😊",
"😸",
"😄"
]
}
}
The same trick works with custom structures.
Conclusion
Swift once again impresses with the convenience of its tools. I hope you enjoyed this article. See you soon!