I'm trying to do this where a background modifier could either accept an optional BackgroundStyle or a Color.
struct ContentView: View {
var background: BackgroundStyle?
var body: some View {
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundStyle(.tint)
Text("Hello, world!")
}
.background(background ?? Color.gray)
.padding()
}
}
#Preview {
ContentView(background: .background)
}
I get this error and I'm not sure how to resolve it.
Cannot convert value of type 'Color' to expected argument type 'BackgroundStyle'
You can use AnyShapeStyle to erase the types, converting both Color and BackgroundStyle to AnyShapeStyle.
.background(background.map(AnyShapeStyle.init) ?? AnyShapeStyle(Color.gray))
The optional here makes this a bit messy. I would use a Bool instead, to indicate whether to use the background style. There is only one instance of BackgroundStyle, anyway.
let useDefaultBackground: Bool
...
.background(
useDefaultBackground ? AnyShapeStyle(.background) : AnyShapeStyle(Color.gray)
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With