Building Robust ViewModels

Feb 28 2025 · Swift 5.9, iOS 17, Xcode 15.3

Lesson 04: Dependency Injection for ViewModels

Demo

Episode complete

Play next episode

Next

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Open TheMet app in the Starter folder. CountView and the commented out lines from the final app of Lesson 3 have been removed.

private let service: TheMetService

init(service: TheMetService = TheMetService(),
     _ maxIndex: Int = 20) {
  self.service = service
  self.maxIndex = maxIndex
}
@Observable class MockMetStore: TheMetStore {
}
override func fetchObjects(for queryTerm: String) async throws {
}
objects = [
  Object(
    objectID: 452174,
    title: "Bahram Gur Slays the Rhino-Wolf",
    creditLine: "Gift of Arthur A. Houghton Jr., 1970",
    objectURL: "https://www.metmuseum.org/art/collection/search/452174",
    isPublicDomain: false,
    primaryImageSmall: ""),
  Object(
    objectID: 241715,
    title: "Terracotta oil lamp",
    creditLine: "The Cesnola Collection, Purchased by subscription, 1874–76",
    objectURL: "https://www.metmuseum.org/art/collection/search/241715",
    isPublicDomain: true,
    primaryImageSmall: "https://images.metmuseum.org/CRDImages/gr/web-large/DP239561.jpg"),
  Object(
    objectID: 452648,
    title: "Gushtasp Slays the Rhino-Wolf",
    creditLine: "Bequest of Monroe C. Gutman, 1974",
    objectURL: "https://www.metmuseum.org/art/collection/search/452648",
    isPublicDomain: true,
    primaryImageSmall: "https://images.metmuseum.org/CRDImages/is/web-large/DP108572.jpg")
]
ContentView(store: MockMetStore())
final class TheMetTests: XCTestCase {
  var sut: TheMetStore!  // add this line
override func setUpWithError() throws {
  try super.setUpWithError()
  sut = TheMetStore()  // add this line
 }
override func tearDownWithError() throws {
  sut = nil  // add this line
  try super.tearDownWithError()
}
func testMaxIndexObjectsFetched() async throws {
  try await sut.fetchObjects(for: "cat")
  XCTAssertLessThanOrEqual(sut.objects.count, sut.maxIndex)
}
See forum comments
Cinema mode Download course materials from Github
Previous: Dependency Injection in MVVM Next: Conclusion