Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I handle default values with images for an optional String property in a Swift struct?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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")
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading