[ad_1]
The difficulty in your instance would not even have something to do with the async code — it has to do with how @State is ready. For instance, this code, with out something async, suffers from the identical “subject”:
struct ContentView: View {
@State non-public var rely = 0
init() {
launchTask()
}
func launchTask() {
let incremented = self.rely + 1
self.rely = incremented
print(self.rely)
}
var physique: some View {
VStack {
Textual content("good day, world")
}
.body(width: 500, peak: 500)
}
}
However, there are a pair issues going incorrect right here:
- Most straight, you can’t and mustn’t rely on
@Statealtering is worth instantly after setting it — it is going to be set on the following render loop. For instance, if you happen to printincrementedin my instance, it’s going to be the worth one expects. In your instance, you might do:
var end result = await self.tweet.replies
print(end result)
self.replies = end result
And, it too, will print the count on end result (assuming your debugging is correct and the async getter is certainly returning outcomes).
- The second subject, though it would not relate on to your downside, is that you must by no means do any ‘work’ in
initin aViewin SwiftUI. As a substitute, use the.process { ... }or.onAppear { ... }modifiers to launch theActivity. In any other case, your operate will run on each init of theView, which could possibly be many many occasions.
[ad_2]
