Skip to content

Instantly share code, notes, and snippets.

@oksuz
Created December 30, 2017 15:11
Show Gist options
  • Save oksuz/4332ee4d9fef848154ef9d3c1d7fbe0d to your computer and use it in GitHub Desktop.
Save oksuz/4332ee4d9fef848154ef9d3c1d7fbe0d to your computer and use it in GitHub Desktop.
generic json serialize/deserialize in swift 4
//
// Credentials.swift
//
// Created by Yunus Oksuz on 30.12.2017.
// Copyright © 2017 Yunus Oksuz. All rights reserved.
//
import Foundation
class Credentials {
let defaults = UserDefaults.standard;
static let instance = Credentials()
var accessToken: AccessToken? {
set {
self.set(key: KEY_ACCESS_TOKEN, data: newValue)
} get {
return self.get(key: KEY_ACCESS_TOKEN, type: AccessToken.self)
}
}
var user: User? {
set {
self.set(key: KEY_USER, data: newValue)
}
get {
return self.get(key: KEY_USER, type: User.self)
}
}
func updateToken(with data: Data) {
self.set(key: KEY_ACCESS_TOKEN, type: AccessToken.self, data: data)
}
func updateUser(with data: Data) {
self.set(key: KEY_USER, type: User.self, data: data)
}
private func set<T : Encodable & Decodable>(key: String, type: T.Type, data: Data) {
do {
let object = try JSONDecoder().decode(type, from: data)
self.set(key: key, data: object)
} catch let err {
debugPrint(err)
}
}
private func set<T: Encodable>(key: String, data: T) {
do {
let payload = try JSONEncoder().encode(data);
self.defaults.set(payload, forKey: key);
} catch let err {
debugPrint(err)
}
}
private func get<T : Decodable>(key: String, type: T.Type) -> T? {
if let payload = self.defaults.value(forKey: key) as? Data {
do {
return try JSONDecoder().decode(type, from: payload);
} catch let err {
debugPrint(err)
}
}
return nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment