Dan
Dan

Reputation: 311

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

}

Upvotes: 6

Views: 6234

Answers (1)

Asperi
Asperi

Reputation: 257603

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.

Upvotes: 25

Related Questions