I am building an app where I need to change the SwiftUI View based on a bool property. The problem is that boolean property value depends on the result of an async operation.
Label("\(tweet.likeCount)", systemImage: isTweetLiked ? "heart.fill": "heart")
private var isTweetLiked: Bool {
Task {
return await model.isTweetLikedByCurrentUser(tweet: tweet)
}
}
Cannot convert return expression of type 'Task<Bool, Never>' to return type 'Bool'
How can I accomplish this?
CodePudding user response:
I can only provide limited insight from the code reference you have given.
Here, you would have to wait for async operation to complete then you can change the state of the property to which properties of Label might be binded.
I tested this code locally, It works.
struct ContentView: View {
@State var likeCount: Int = 0
@State var isTweetLiked: Bool = false
var body: some View {
Label("\(likeCount)", systemImage: isTweetLiked ? "heart.fill": "heart").onAppear{
Task {
await updateUsers()
}
}
}
func updateUsers() async {
do {
let isLiked = await model.isTweetLikedByCurrentUser(tweet: tweet)
DispatchQueue.main.async {
likeCount = isLiked ? likeCount 1 : isLiked
isTweetLiked = isLiked
}
} catch {
print("Oops!")
}
}
}
Certainly, I tested with a sample API, but I have changed the code to resemble your code for ease of understanding.
Also, I am calling the updateUsers from onAppear. Which might not be what you want, you can call it from a place which suits your custom requirements.