Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swiftui ternary operator in view body

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")

}

like image 661
Dan Avatar asked Dec 10 '22 01:12

Dan


1 Answers

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.

like image 168
Asperi Avatar answered Jan 15 '23 09:01

Asperi