Skip to content

Instantly share code, notes, and snippets.

@TheWorstProgrammerEver
Created March 5, 2022 07:58
Show Gist options
  • Save TheWorstProgrammerEver/84535f7654dc7c7f056adaad3286a8f9 to your computer and use it in GitHub Desktop.
Save TheWorstProgrammerEver/84535f7654dc7c7f056adaad3286a8f9 to your computer and use it in GitHub Desktop.
Swift Cache Service (leveraging Codable / JSON support) and simple implementation with UserDefaults
import Foundation
protocol CacheService {
func load<T: Cachable>(_ identifier: String) throws -> T?
func save<T: Cachable>(_ identifier: String, _ cachable: T) throws
func clear<T: Cachable>(_ type: T.Type) throws
func clear(_ identifier: String) throws
}
extension CacheService {
func load<T: Cachable>(_ type: T.Type) throws -> T? {
try load()
}
func load<T: Cachable>() throws -> T? {
try load(.init(describing: T.self))
}
func save<T: Cachable>(_ cachable: T) throws {
try save(String(describing: T.self), cachable)
}
}
typealias Cachable = Codable
import Foundation
class UserDefaultsCacheService : CacheService {
func load<T: Cachable>(_ identifier: String) throws -> T? {
do {
return try UserDefaults
.standard
.data(forKey: identifier)
.map(decode)
} catch {
return nil
}
}
func save<T: Cachable>(_ identifier: String, _ cachable: T) throws {
do {
let data = try encode(cachable)
UserDefaults
.standard
.setValue(data, forKey: identifier)
} catch {
throw error
}
}
func clear<T: Cachable>(_ type: T.Type) throws {
try clear(String(describing: T.self))
}
func clear(_ identifier: String) throws {
UserDefaults
.standard
.removeObject(forKey: identifier)
}
fileprivate func decode<T: Decodable>(_ json: Data) throws -> T {
try decoder.decode(T.self, from: json)
}
fileprivate func encode<T: Encodable>(_ value: T) throws -> Data {
try encoder.encode(value)
}
}
fileprivate let encoder: JSONEncoder = .init()
fileprivate let decoder: JSONDecoder = .init()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment