What is the difference between putting await at the start of an assignment line or after the = operator?
For example, this code compiles correctly with both options.
@MainActor class AppleList: ObservableObject {
@Published var apples: [Apple]
private let fetcher = AppleFetcher()
init(apples: [Apple]) {
self.apples = apples
}
func load() async {
// BOTH OF THESE LINES BUILD, BUT WHAT IS THE DIFFERENCE?
apples = await fetcher.fetch()
await apples = fetcher.fetch()
}
}
I am only seeing examples in the Meet async/await in Swift video that put await after the = operator.
I am uncertain if this is relevant, but I am also noticing most examples are assigning to local symbols instead of properties.
The code of AppleFetcher, if needed.
private actor AppleFetcher {
func fetch() async -> [Apple] {
// Fake a network call.
try? await Task.sleep(until: .now + .seconds(6), clock: .continuous)
return [
Apple(name: "honeycrisp", seeds: 47),
Apple(name: "golden", seeds: 56),
]
}
}
I found this assertion from Explore structured concurrency in Swift, but it does not really explain in enough detail for me to fully understand.
you write “try await” on the right side of the let, because that’s where an error or suspension would be observed.
If there is not a difference in my example, under what circumstances, if any, would there be a difference?
Functionally they are the same. Here is the assembly of the two renditions. The addresses change between the builds (as they it will between any two builds), but the code is the same. Below I will toggle between the breakpoints of the two renditions (making it easier to see where they differ and where they do not):

That having been said, the first approach, apples = await fetcher.fetch(), is the accepted convention and, as noted by vadian, is what is explicitly suggested in The Swift Programming Language: Concurrency.
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