inside a swiftyui body, based on news.urlToImage value, i need to be able to load either another view (LOadRemoteImageView, which is just another view which is accepting an optional url string to load remote image), either to display an Text string "no image url".
Following the syntax below, it works fine
if news.urlToImage == nil {
Text("no image url")
}else {
LoadRemoteImageView(withURL: news.urlToImage!).frame(width: 140, height: 140)
}
however when trying to inline the code, it fails with no correct error message by intellisense
news.urlToImage == nil ? Text("no image") : LoadRemoteImageView(withURL: news.urlToImage!)
also tried to use map to display either of the two views if urlToImage: String is not nil, but fails as well
news.urlToImage.map {
$0 != nil ? LoadRemoteImageView(withURL: $0) : Text("no image")
}
It is all about types ... result of line expression must generate single type. So if you so like ternary operator you should use it like
news.urlToImage == nil ? AnyView(Text("no image")) :
AnyView(LoadRemoteImageView(withURL: news.urlToImage!))
or something similar... as for me regular if/else
is better.
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