DEV Community

yipcodes
yipcodes

Posted on

Swift Codable Protocol

KISS: Codable protocol helps to translate json data format into a class object.

KISS Diagram:

Image description

Here is a short extraction from this well written article by wunderman thomson:

Codable is the combined protocol of Swift’s Decodable and Encodable protocols. Together they provide standard methods of decoding data for custom types and encoding data to be saved or transferred.

Below is an example of just how simple Codable can make the data parsing process. Notice that the first object, parsed without Codable, takes about 19 lines of code. The second object, using Codable, takes just 5 lines of code.

// JSON Data:
{
 "id": 1234,
 "src": "//api.someHost.com/version/someImageName.jpg",
 "caption": null
}


// Old Object:
struct Photo {
 let id: Int
 let src: URL
 let caption: String?

 init?(json: [String: Any]) {
 guard
 let id = json[“id”] as? Int,
 let srcString = json["src"] as? String,
 let src = URL(string: srcString)
 else { return nil }

 let caption = json["caption"] as? String

 self.id = id
 self.src = src
 self.caption = caption
 }
}


// New Codable Object:
struct Photo: Codable {
 let id: Int
 let src: URL
 let caption: String?
}
Enter fullscreen mode Exit fullscreen mode

Sentry mobile image

Improving mobile performance, from slow screens to app start time

Based on our experience working with thousands of mobile developer teams, we developed a mobile monitoring maturity curve.

Read more

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay