ArchitectureMidMCQ
What is the Repository pattern?
Test your knowledge:
Explanation & Code
Answer: The Repository pattern abstracts the data layer behind a protocol. The rest of the app doesn't know or care whether data comes from a network, database, or cache.
Code Example:
// Protocol — defines what the repo can do
protocol ArticleRepository {
func fetchAll() async throws -> [Article]
func fetch(id: String) async throws -> Article
func save(_ article: Article) async throws
}
// Real implementation — hits network + caches to CoreData
class RemoteArticleRepository: ArticleRepository {
func fetchAll() async throws -> [Article] {
let articles = try await api.getArticles()
cache.save(articles)
return articles
}
}
// Test implementation — returns fake data instantly
class MockArticleRepository: ArticleRepository {
func fetchAll() async throws -> [Article] {
return [Article.mock()]
}
}
// ViewModel uses the protocol — doesn't know which implementation it has
class ArticleViewModel: ObservableObject {
private let repo: ArticleRepository
init(repo: ArticleRepository) { self.repo = repo }
}
Rate your understanding: