Generic View Returning a Closure Option

Hi. I am new to SwiftUI and i am not sure what the right term for this is. Hoping someone can guide me

Take this generic view for example (this one is incorrect since if i pass a view as parameter, how can it use the fetched data).

struct FetchUrlContentView<Content: View>: View {
  var url: String?
  @State var loading = true
  @State var error = false
  @State var view: Content
   
  var body: some View {
    HStack {
      if !NetworkTool.hasInternet() {
        NoInternetView()
      }
      else if loading {
        LoadingProgressView()
      }
      else if error {
        SomethingWrongView()
      }
      else {
        view
      }
    }
    .task {
      if let urlLink = self.url {
        fetchContentFromUrl(url: urlLink, { data in
          // Supposed to use data to the view here but it won't be generic.
          // any ideas?
          self.loading = false
        })
      }
      else {
        self.loading = false
        self.error = true
      }
    }
}

What i am looking for is something of a way to keep on reusing FetchUrlContentView such that after data is fetched, i could call it like this

FetchUrlContentView(url: "https://www.test.com/", loading: true) { data in MyView(data) }

where MyView contains something like Text(data.description)

If I understand your question, you could:

  • use environment var
  • just make url a State var
  • and not pass Content as parameter
Generic View Returning a Closure Option
 
 
Q