Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import Foundation
- enum PersistenceActionType {
- case add, remove
- }
- enum PersistenceManager {
- static private let defaults = UserDefaults.standard
- enum Keys { static let favorites = "favorites" }
- static func updateWith(favorite: Post, actionType: PersistenceActionType, completed: @escaping (RCError?) -> Void) {
- retrieveFavorites { result in
- switch result {
- case .success(var favorites):
- switch actionType {
- case .add:
- guard !favorites.contains(favorite) else {
- completed(.alreadyInFavorites)
- return
- }
- favorites.append(favorite)
- case .remove:
- favorites.removeAll { $0.data.id == favorite.data.id }
- }
- completed(save(favorites: favorites))
- case .failure(let error):
- completed(error)
- }
- }
- }
- static func retrieveFavorites(completed: @escaping (Result<[Post], RCError>) -> Void) {
- guard let favoritesData = defaults.object(forKey: Keys.favorites) as? Data else {
- completed(.success([]))
- return
- }
- do {
- let decoder = JSONDecoder()
- let favorites = try decoder.decode([Post].self, from: favoritesData)
- completed(.success(favorites))
- } catch {
- completed(.failure(.unableToFavorite))
- }
- }
- static func save(favorites: [Post]) -> RCError? {
- do {
- let encoder = JSONEncoder()
- let encodedFavorites = try encoder.encode(favorites)
- defaults.set(encodedFavorites, forKey: Keys.favorites)
- return nil
- } catch {
- return .unableToFavorite
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement