Codable in iOS

Mr.Javed Multani
2 min readOct 3, 2020

Codable is added with Xcode 9, iOS 11 and Swift 4. Codable is used to make your data types encodable and decodable for compatibility with external representations such as JSON.

Codable use to support both encoding and decoding, declare conformance to Codable, which combines the Encodable and Decodable protocols. This process is known as making your types codable.

Use of Codable with JSONEncoder and JSONDecoder in Swift 4

Let’s Take an Example with Structure of Movie, here we have defined the structure as Codable. So, We can encode and decode it easily.

struct Movie: Codable {
enum MovieGenere: String, Codable {case horror, skifi, comedy, adventure, animation
}var name : String
var moviesGenere : [MovieGenere]
var rating : Int
}

We can create a object from movie like as:

let upMovie = Movie(name: “Up”, moviesGenere: [.comedy , .adventure, .animation], rating : 4)

The upMovie contains the name “Up” and it’s movieGenere is comedy, adventure and animation witch contains 4 rating out of 5.

Encode

JSONEncoder is an object that encodes instances of a data type as JSON objects. JSONEncoder supports the Codable object.

// Encode datalet jsonEncoder = JSONEncoder()
do {let jsonData = try jsonEncoder.encode(upMovie)
let jsonString = String(data: jsonData, encoding: .utf8)
print("JSON String : " + jsonString!)}
catch { }

--

--

Mr.Javed Multani

Software Engineer | Certified ScrumMaster® (CSM) | UX Researcher | Youtuber | Tech Writer