Chapter 6: Question on "Dependency Injection"

Always trying to learn, so I’m curious about the code added to RegisterView.swift to initialize the keyboardHandler property:

init(keyboardHandler: KeyboardFollower) {
  self.keyboardHandler = keyboardHandler
}

Why is this code needed? The project seems to work fine without it, the var is not initialized on declaration, so omitting the object when referencing RegisterView is a compile-time error, and passing it in the call to RegisterView initializes the property implicitly.

Hi @fischej, when you say the project seems to work fine without it, do you mean the project works fine without the initializer, or do you mean the project works fine without the initializer as well as the defineid property itself (e.g. “@ObservedObject var keyboardHandler: KeyboardFollower)?

The former. The project seems to function the same way whether or not the block comment is there:

struct RegisterView: View {
    @EnvironmentObject var userManager: UserManager
    @ObservedObject var keyboardHandler: KeyboardFollower
    
    /*
     init(keyboardHandler: KeyboardFollower) {
     self.keyboardHandler = keyboardHandler
     }
     */
    
    var body: some View {
...

Hi, that’s probably a bug in my code - the keyboard handler is not actually needed anymore because SwiftUI handles that by itself.