I am attempting to implement Dependency Injection with a SwiftUI View
by assigning the Type of a View to a static var that conforms to a CustomViewInterface
protocol.
static var MyCustomView: any CustomViewInterface.Type = CustomView.self
The goal being to inject any View
that conforms to that protocol and initialize it inside the receiving class.
When I initialize the custom SwiftUI View
inside the body
block of the ContentView
I get the error
Type 'any CustomViewInterface' cannot conform to 'View'
.
Although when I print out the type(of:
of the View Type it is CustomView
(not CustomViewInterface
) I don't understand why the Type
is different when it's initialized inside the body
block of the ContentView
vs in the initializer of the DefaultComponentImplementation
class.
My question is, how can I initialize a custom SwiftUI View from a static var that conforms to a protocol. The end goal is to use Dependency Injection for SwiftUI Views.
import SwiftUI
struct ContentView: View {
let defaultComponenetImplementaion = DefaultComponentImplementation()
var body: some View {
VStack {
CustomView(title: "cat") // this works
DefaultComponentImplementation.MyCustomView.init(title: "mouse") // error: Type 'any CustomViewInterface' cannot conform to 'View'
}
}
}
protocol CustomViewInterface: View {
var title: String { get set }
init(title: String)
}
struct CustomView: CustomViewInterface {
var title: String
var body: some View {
Text(title)
}
}
class DefaultComponentImplementation {
static var MyCustomView: any CustomViewInterface.Type = CustomView.self
init() {
print(type(of: DefaultComponentImplementation.MyCustomView.init(title: "cat"))) // prints CustomView
}
}