Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI - Returning an opaque type in a protocol

Tags:

swift

swiftui

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?

like image 956
Above The Gods Avatar asked Nov 19 '25 05:11

Above The Gods


1 Answers

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

Update: added ViewBulider, re-tested with Xcode 13.4 / iOS 15.5

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()
        }
    }
}
like image 130
Asperi Avatar answered Nov 21 '25 10:11

Asperi