How do I implement a repository pattern over Core Data in Swift?

The repository pattern is a design pattern that provides a way to encapsulate the logic required to access data sources. By implementing a repository pattern over Core Data in Swift, you can separate your data access logic from your business logic, making your codebase cleaner and more maintainable.

Below is an example of how to implement a basic repository pattern for Core Data:

import Foundation import CoreData // Protocol defining the methods of the repository protocol UserRepositoryProtocol { func fetchAllUsers() -> [User] func saveUser(name: String, age: Int) } // CoreData Entity class @objc(User) public class User: NSManagedObject { @NSManaged public var name: String? @NSManaged public var age: Int16 } // Implementation of the repository class UserRepository: UserRepositoryProtocol { let context: NSManagedObjectContext init(context: NSManagedObjectContext) { self.context = context } func fetchAllUsers() -> [User] { let request: NSFetchRequest = User.fetchRequest() do { return try context.fetch(request) } catch { print("Error fetching users: \(error)") return [] } } func saveUser(name: String, age: Int) { let user = User(context: context) user.name = name user.age = Int16(age) do { try context.save() } catch { print("Error saving user: \(error)") } } }

Swift Core Data repository pattern software design patterns data management