Last active
January 26, 2018 13:21
-
-
Save dedeexe/3d568b65aab04b7b4baf4358ad6d8ef9 to your computer and use it in GitHub Desktop.
Protocol to encode JSON to Swift object
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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