Currently, I have a protocol Media which has the method displaySummary() -> some View. The problem is, an opaque type cannot be returned in a protocol, as far as I know.
protocol Media {
func displaySummary() -> some View
}
The implementation code looks like the following:
final class Playlist: Media {
func displaySummary() -> some View {
return HStack {
Text("Summary")
.padding(.all)
.background(Color.black)
}
}
And in the ContentView, I have the following:
let media: Media = Playlist()
var body: some View {
ScrollView(.horizontal, showsIndicators: false) {
media.displaySummary()
}
}
Is there a way to make this work in SwiftUI?
Here is variant using protocol associatedtype, actually SwiftUI native approach, if we see in its auto-generated module. This allows to avoid type-erasure wrappers and use view directly.
Tested with Xcode 11.4 / iOS 13.4
protocol Media {
associatedtype Summary : View
func displaySummary() -> Self.Summary
}
final class Playlist: Media, Identifiable {
@ViewBuilder
func displaySummary() -> some View {
HStack {
Text("Summary")
.padding(.all)
.background(Color.black)
}
}
}
struct PlaylistView: View {
let playlist = Playlist()
var body: some View {
ScrollView(.horizontal, showsIndicators: false) {
playlist.displaySummary()
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With