How to fix "Generic parameter 'Icon' could not be inferred"?

import SwiftUI

struct Foo<Icon: View>: View {
  // User provide icon factory, nil for no icon
  var icon: (() -> Icon)?   // how to default to nil without "Generic parameter 'Icon' could not be inferred"?
  var body: some View {
    VStack {
      Text("Icon:")
      icon?()
    }
  }
}
struct ContentView: View {
  var body: some View {
    VStack {
      Foo(icon: { Image(systemName: "globe")})
      Foo<Never>() // Generic parameter 'Icon' could not be inferred
//        ^^^^^  anyway to avoid having to do this? nil<Never>?
    }
    .padding()
  }
}

#Preview {
  ContentView()
}

I need to use var icon: (() -> Icon) because the parent needs to provide different icon view depending on parent view state.

Maybe there’s a better way but adding these initializers to Foo allows creating one as Foo()

init(icon: @escaping () -> Icon) { self.icon = icon }
init() where Icon == Never {}
2 Likes

:+1:

I put the 2nd init in a extension so to keep the synthesized init

1 Like