UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.