I recently converted some of my code which originally used Type-Erasure to use the new Swift 5.7 any
existential.
However, I'm getting some issues when trying to use the any
keyword with already implemented generic types.
I'm running this on Xcode 14 Beta 2.
Here is an example:
protocol Provider<Value> {
associatedtype Value
func get() -> Value
}
struct S {
var stringProvider: any Provider<String>
}
Here is a very simple struct S
which has a member stringProvider
. I use the any
keyword here instead of making any Provider<String>
generic because I would like to be able to reassign stringProvider
to a different value later on (which has a different type).
struct ProviderView<P: Provider>: View {
let provider: P
var body: some View {
Text(String(describing: type(of: provider.get())))
}
}
Now here I have a ProviderView
SwiftUI struct, which takes in a Provider
and does stuff with it.
struct DummyProvider: Provider {
typealias Value = String
func get() -> String {
"Hello World!"
}
}
And this is just a dummy Provider
implementation which just returns a string.
This all works fine, the problem comes when I try to use ProviderView
with an existential any
.
struct ContentView: View {
let s = S(stringProvider: DummyProvider())
var body: some View {
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundColor(.accentColor)
ProviderView(provider: s.stringProvider) // This is the erroring line
}
}
}
I get an error saying Type 'any Provider<String>' cannot conform to 'Provider'
.
I think I know why, it's because ProviderView
cannot have an any
existential as a generic argument.
I was wondering, what are the possible ways around this, other than type erasure?
I also read SE-0352, here: swift-evolution/0352-implicit-open-existentials.md at main · apple/swift-evolution · GitHub
It says:
When
T
or aT
-rooted associated type appears in a non-covariant position in the result type,T
cannot be bound to the underlying type of an existential value because there would be no way to represent the type-erased result. This is essentially the same property as descibed for the parameter types that prevents opening of existentials, as described above. For example:
func cannotOpen7<T: P>(_ value: T) -> X<T> { /*...*/ }
I was kinda confused by what this means. I was wondering, could someone clarify this?