Skip to content

Instantly share code, notes, and snippets.

@dedeexe
Last active January 26, 2018 13:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dedeexe/3d568b65aab04b7b4baf4358ad6d8ef9 to your computer and use it in GitHub Desktop.
Save dedeexe/3d568b65aab04b7b4baf4358ad6d8ef9 to your computer and use it in GitHub Desktop.
Protocol to encode JSON to Swift object
//
// Serializable.swift
//
// Created by dede.exe on 14/10/17.
// Copyright © 2017 dede.exe. All rights reserved.
//
import Foundation
public protocol Serializable : Codable {
init?(json:String)
init?(json:Data)
func serialize() -> Data?
}
extension Serializable {
public init?(json:Data) {
let decoder = JSONDecoder()
guard let value = try? decoder.decode(Self.self, from: json) else { return nil }
self = value
}
public init?(json:String) {
let decoder = JSONDecoder()
guard let data = json.data(using: .utf8), let value = try? decoder.decode(Self.self, from: data) else { return nil }
self = value
}
public func serialize() -> Data? {
let coder = JSONEncoder()
return try? coder.encode(self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment