I have the following code:
@State var type: String = "color"
@State var color: Color = Color(.black)
@State var gradient: LinearGradient = LinearGradient(colors: [.orange, .red],
startPoint: .top,
endPoint: .center)
Text("Hello World!").foregroundStyle(type == "color" ? color : gradient)
It complains that color and gradient aren't the same type. However, there is no conditional logic for modifiers. So, how can I achieve the desired outcome?
Note: I have around 14 other modifiers, so a wrapping if else won't work as some other modifiers have the same issue, so there will be too many if else combinations.
Wrap the Colour and the LinearGradient in a AnyShapeStyle to achieve type erasure:
@State var type: String = "color"
@State var color: Color = Color(.black)
@State var gradient: LinearGradient = LinearGradient(colors: [.orange, .red],
startPoint: .top,
endPoint: .center)
Text("Hello World!")
.foregroundStyle(type == "color"
? AnyShapeStyle(color) : AnyShapeStyle(gradient))
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