somu
(somu)
1
Hi,
I have the following code that throws a compilation error.
Overview
- I have an
async let p1 statement
- Then I have 2 statements that
await on p1
- Removing one of those 2 awaits removes the error
Compilation error:
Immutable value 'p1' may only be initialized once
Question:
- What causes this error? (is the error a bit misleading?, or may be I don't understand it)
- How to fix this issue?
- So every time I access
p1 should I use await p1?
Tested on:
- Xcode Version 13.0 beta (13A5155e)
- iOS project that supports only iOS 15.0
- macOS Big Sur (11.4)
Code
func f1() {
async {
async let p1 = computePrice() //Immutable value 'p1' may only be initialized once
print(await p1)
let k = await p1
}
}
func computePrice() async -> Int {
await withCheckedContinuation { continuation in
DispatchQueue.main.asyncAfter(deadline: .now() + 4) {
continuation.resume(returning: 10)
}
}
}
Just a guess, try moving print further down and access k Instead print(k).
somu
(somu)
3
Thanks @DevAndArtist print(k) works, but I am just wondering what is wrong with the original code.
I haven‘t read through the async let proposal but I would guess that it‘s illegal to call await more than once on an async let constant. Please look up the detailed design in the original proposal.
Thank you, then I have no idea what the issue is. The compile seems to output a misleading message, which means there is likely still room for improvement. I guess it‘s something for bugs.swift.org then.
somu
(somu)
7