TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

SOLVED: View with an optional @ViewBuilder parameter - Avoiding "generic parameter could not be inferred"?

Forums > SwiftUI

I have the following View:

struct ReferenceRow<Content: View>: View {

  let title: String
  let subtitle: String?
  let icon: Image?
  let secondary: () -> Content?

  init(
    title: String,
    subtitle: String? = nil,
    icon: Image? = nil,
    @ViewBuilder secondary: @escaping () -> Content? = { nil }
  ) {
    self.title = title
    self.subtitle = subtitle
    self.icon = icon
    self.secondary = secondary
  }

  var body: some View {
    // ...
  }

}

However, if I try to omit secondary (such as with ReferenceView(title: "Title", subtitle: "Subtitle"), Xcode complains that "Generic parameter 'Content' could not be inferred". Is there any way to make this work?

3      

In my understanding you can't do it this way. Swift needs to know which type Content will be when ReferenceRow is initiated.

When you omit secondary then Swift doesn't know which type Content will have. To be specific. If you omit secondary you have to initiate ReferenceRow<YourViewTypeHere>(title: "Title", subtitle: "Subtitle") like this.

3      

Thanks. A little disappointing. I decided to remove the generic entirely after realizing the Content was always going to be a color accent, and that its shape and position is invariable.

3      

Hacking with Swift is sponsored by String Catalog.

SPONSORED Get accurate app localizations in minutes using AI. Choose your languages & receive translations for 40+ markets!

Localize My App

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.