What is Codable protocol in Swift?

What is Codable protocol in Swift?

The Codable protocol is used to go from a JSON data object to an actual Swift class or struct. This is called decoding, because the JSON data is decoded into a format that Swift understands. It also works the other way: encoding Swift objects as JSON. The centerpiece of this workflow is Swift's Codable protocol.

Almost every app has its own user data that has to be saved when the user closes an app and still exists when the app will be opened the next time. To do so, the info that lives in memory must be encoded to a form of data that can be written to a file. The Codable protocol makes it possible by creating a key/value pairs from your object’s property names and holds it that can then be used by an Encoder or Decoder object.

Let’s Start

Most Swift types that are used in the standard library already conform to Codable. If all your data types conform to Codable, the only thing left to do is to add Codable to the declaration and the everything will be autogenerated for you.

struct Student: Comparable, Codable {

        static func < (lhs: Student, rhs: Student) -> Bool {
            return lhs.secondName < rhs.secondName
        }

        var firstName: String
        var secondName: String
        var faculty: String
    }

The encode(_:) method on JSONEncoder is considered a throwing function, a special type of Swift function that can return specific types of errors. Syntax try? allows a function to return an optional value. If there’s no error, the optional will hold the expected value; Otherwise, it will be nil.

The following example will show how to encode data with JSONEncoder.

import Foundation

    let student = Student(firstName: "Mark", secondName: "Williams", faculty: "CIE")

    struct Student: Codable {
        var firstName: String
        var secondName: String
        var faculty: String
    }

    let jsonEncoder = JSONEncoder()
    if let jsonData = try? JSONEncoder().encode(student),
    let jsonString = String(data: jsonData, encoding: .utf8) {
        print(jsonString)
    }

Image for post

The Codable protocol will come in handy in future lessons when you will working with saving data or web services.

ios programming mobile-app-development swift technology json

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

How long does it take to develop/build an app?

This article covers A-Z about the mobile and web app development process and answers your question on how long does it take to develop/build an app.

Best Mobile App Development Company | Android and iOS Apps

iPrism Tech is a one of the best and offshore mobile app development company in India, Saudi Arabia and USA. We are a major providers of android, iphone and ipad mobile app development services at economical prices.

Top iOS Mobile App Development Agency in New York

Are you looking for a [Top iOS Mobile App Development Agency in New York]**(https://www.appcluesinfotech.com/ios-app-develop**ment-company/ "Top iOS Mobile App Development Agency in New York") for your app projects? Then AppClues Infotech is the...

Mobile App Development North Carolina

Mobile App Development North Carolina In the era of globalization, technology has forced the businesses and industries to jump into the space of competition. Technology has both tangible and intangible benefits that help businesses from different ind...

Top Mobile App Developers & Leading App Development Companies in UK

Profusely examined top Mobile App Development companies in UK with ratings & reviews to help find the best Mobile App Development solution providers.