I’m working with an optional struct in Swift, where the default value is expected to be a string. However, I’d like to handle a scenario where the default value can also be an image. Here’s the code I’m using:
Text(quotes.quote ?? Image(systemName: "circle.dashed") )
Can someone please guide me on how to convert this image fallback into a string when quotes.quote is nil?
My expectation was to set a default value for Text as a string, and if quotes.quote is nil, I wanted to use an image (in this case, "circle.dashed") as the fallback.
>Solution :
If you’d like to write it with a ternary operator, a single expression must return single type, so you would have to write:
quotes.quote != nil ? AnyView(Text(quotes.quote!)) : AnyView(Image(systemName: "circle.dashed"))
However, this is a bit hard on the eye, and I’d like to avoid the force-unwrap:
if let quote = quotes.quote {
Text(quote)
} else {
Image(systemName: "circle.dashed")
}