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

Top comments (0)