Michael Long
1 min readNov 13, 2019

--

I’m still working on various solutions to service dependencies.

But my current thinking is that I might forgo environmentObject (and its issues) altogether and consider using a variant of my dependency injection system (Resolver) in SwiftUI. Something like…

struct ContentView: View {    @InjectedObject var user: UserService    var body: some View {
VStack {
Text(user.name)
Text(user.data ?? "n/a")
Button(action: {
self.user.update()
}) {
Text("Update")
}
}
}
}

The InjectedObject wrapper is a version of my Injected wrapper that performs automatic dependency injection using property wrapper annotation while at the same time exposing an ObservableObject to SwiftUI.

UserService might look like…

class UserService: ObservableObject {    @Published var name = "Michael"    
@Published var data: String?
@Injected var anotherDependency: SecondDependentService func update() {
anotherDependency.fetch {
self.data = $0
}
}
}

Where SecondDependentService is a behind-the-scenes service and not necessarily a SwiftUI ObservableObject.

--

--

Michael Long
Michael Long

Written by Michael Long

I write about Apple, Swift, and SwiftUI in particular, and technology in general. I'm also a Lead iOS Engineer at InRhythm, a modern digital consulting firm.

Responses (1)