What is Codable in Swift

Codable was introduced in Swift since 4.0, which is used for encoding and decoding objects into JSON. From its definition we can see it is just the combination of Decodable and Encodable:

public typealias Codable = Decodable & Encodable

Example of using Codable:

Define a custom object with Codable:

struct NoteModel: Codable{
    let userName: String
    let latitude: Double
    let longitude: Double
    let text: String
    let createDateTime: String
    // mapping the keys from data
    enum CodingKeys: String, CodingKey {
        case userName       = "username"
        case latitude       = "latitude"
        case longitude      = "longitude"
        case text           = "text"
        case createDateTime = "create_datetime"

comments powered by Disqus