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

What is Codable protocol in Swift?
1.40 GEEK