-
Notifications
You must be signed in to change notification settings - Fork 1
/
CodableHelpers.swift
41 lines (34 loc) · 1.05 KB
/
CodableHelpers.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
//
// CodableHelpers.swift
// ArrayInspire
//
// Created by Prashant on 30/08/18.
// Copyright © 2018 Prashant. All rights reserved.
//
import Foundation
import Alamofire
class CodableHelper<T:Codable> {
func decode(json:Result<Any>) -> (object:T?,error:Error?) {
switch json {
case .success(let value):
do {
let data = try JSONSerialization.data(withJSONObject: value, options: [])
let object = try JSONDecoder().decode(T.self, from: data)
return (object,nil)
} catch {
return (nil,error)
}
case .failure(let error):
return (nil,error)
}
}
func encode(object:T) -> (object:Any?,error:Error?) {
do {
let data = try JSONEncoder().encode(object)
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
return (json,nil)
} catch {
return (nil,error)
}
}
}