Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
import UIKit
// Use Basic Encoder & Decoder By Codable
struct Book: Codable {
var title: String
var author: String
var price: Int
let book1 = Book(title: "Hello World", author: "hcn1519", price: 10000)
let encoder = JSONEncoder()
if let encodedData = try? encoder.encode(book1) {
let decoder = JSONDecoder()
let decodedData = try? decoder.decode(Book.self, from: encodedData)
// Make Serializable Protocol
protocol Serializable: Codable {
func serialize() -> Data?
extension Serializable {
func serialize() -> Data? {
let encoder = JSONEncoder()
return try? encoder.encode(self)
struct Laptop: Serializable {
var name: String
var type: String
let macbook = Laptop(name: "MacBookPro", type: "15 mid")
if let dataOfMacbook = macbook.serialize() {
let decoder = JSONDecoder()
let decodedMacbook = try? decoder.decode(Laptop.self, from: dataOfMacbook)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment