Skip to content

Instantly share code, notes, and snippets.

@bestiosdeveloper
Created May 15, 2020 07:39
Show Gist options
  • Save bestiosdeveloper/6694e1ad782e1b2c08f054be3eea3243 to your computer and use it in GitHub Desktop.
Save bestiosdeveloper/6694e1ad782e1b2c08f054be3eea3243 to your computer and use it in GitHub Desktop.
//
// CodableExtensionExample.swift
//
// Created by Pramod Kumar on 05/15/20.
// Copyright © 2020 Swift Commmunity. All rights reserved.
//
import UIKit
let json = """
{
"body": "It is awesome!",
"replySent": true,
"senderName": "Swift Commmunity"
}
"""
struct Message: Codable {
var body: String
var replySent: Bool
let senderName: String
}
func save(message: Message) {
//Do great things with model object
}
guard let data = json.data(using: .utf8) else {
fatalError("No able to convert from String to Data")
}
extension Encodable {
func encoded() throws -> Data {
return try JSONEncoder().encode(self)
}
}
extension Data {
func decoded<T: Decodable>() throws -> T {
return try JSONDecoder().decode(T.self, from: self)
}
}
// We can always provide the type, whilst making
// the call site read very nicely.
let messageObj = try data.decoded() as Message
// And if not, the compiler can often infer the
// type from the current context that we want
// to decode. Because we are using generic type
// in the decoded() method.
try save(message: data.decoded())
// We can directly encode our model object to data
let encodedMessage = try messageObj.encoded()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment