Take this simple view. It has a @StateObject
that is used within the view to automatically load and parse some data. I have many of these views with different loaders and parsers.
struct SomeView {
@StateObject var loader: Loader<SomeParser> = Loader<SomeParser>()
var body: some View {
// Some body that uses the above loader
VStack {
// ...
}
}
}
The loaders are set to use @MainActor
and since the swift 5.6
update I get the new warning about initiating these with a default value and that it will be an error in swift 6
Expression requiring global actor 'MainActor' cannot appear in default-value expression of property '_loader'; this is an error in Swift 6
There's a simple fix, as explained here. We simply set it in the init
struct SomeView {
@StateObject var loader: Loader<SomeParser>
init() {
self._loader = StateObject(wrappedValue: Loader<SomeParser>())
}
var body: some View {
// Some body that uses the above loader
VStack {
// ...
}
}
}
Now the issue I have, is that I have 20+ of these views, with different loaders and parsers and I have to go through each and add this init
.
I thought, let's simply create a class that does it and subclass it. But it's a View
struct
so that's not possible to subclass.
Then I had a go at using a protocol
, but I couldn't figure out a way to make it work as overriding the init()
in the protocol doesn't let you set self.loader = ...
Is there a better way to do this, or is adding an init
to every view the only way?