The Repository pattern helps keep your app organized by separating data access from the rest of your code. It acts like a middleman between your app and data sources.
0
0
Repository pattern in iOS Swift
Introduction
When you want to keep your code clean and easy to change.
When your app gets data from different places like a server or local storage.
When you want to test your app easily without real data sources.
When you want to change where data comes from without changing the whole app.
Syntax
iOS Swift
protocol Repository {
associatedtype Item
func fetchAll() -> [Item]
func add(_ item: Item)
func remove(_ item: Item)
}This is a simple protocol defining what a repository should do.
Use associatedtype to make it work with any data type.
Examples
This example shows a UserRepository that stores users in memory.
iOS Swift
struct User {
let id: Int
let name: String
}
class UserRepository: Repository {
typealias Item = User
private var users = [User]()
func fetchAll() -> [User] {
return users
}
func add(_ item: User) {
users.append(item)
}
func remove(_ item: User) {
users.removeAll { $0.id == item.id }
}
}This example shows a repository that could fetch users from a server.
iOS Swift
class RemoteUserRepository: Repository { typealias Item = User func fetchAll() -> [User] { // Imagine fetching from a server here return [User(id: 1, name: "Alice")] } func add(_ item: User) { // Send user to server } func remove(_ item: User) { // Remove user from server } }
Sample App
This program creates a user repository, adds two users, then removes one. It prints the list of users before and after removal.
iOS Swift
import Foundation struct User: Equatable { let id: Int let name: String } protocol Repository { associatedtype Item func fetchAll() -> [Item] func add(_ item: Item) func remove(_ item: Item) } class UserRepository: Repository { typealias Item = User private var users = [User]() func fetchAll() -> [User] { return users } func add(_ item: User) { users.append(item) } func remove(_ item: User) { users.removeAll { $0.id == item.id } } } // Using the repository let repo = UserRepository() repo.add(User(id: 1, name: "Alice")) repo.add(User(id: 2, name: "Bob")) print("Users after adding:", repo.fetchAll()) repo.remove(User(id: 1, name: "Alice")) print("Users after removing Alice:", repo.fetchAll())
OutputSuccess
Important Notes
The Repository pattern helps you swap data sources easily without changing your app logic.
Keep repository methods simple and focused on data operations.
Use protocols to define repository behavior for flexibility and testing.
Summary
The Repository pattern separates data access from app logic.
It makes your code cleaner and easier to maintain.
You can switch data sources without changing the rest of your app.