Async let - await - compilation error

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

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.

It is not:

Currently, it is required to cover every reference to a async let using the appropriate try and await keywords [...]
This is a simple rule and allows us to bring the feature forward already. It might be possible to employ control flow based analysis to enable "only the first reference to the specific async let on each control flow path has to be an await ", as technically speaking, every following await will be a no-op and will not suspend as the value is already completed, and the placeholder has been filled in.

2 Likes

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.

@xwu Thanks a lot for the clarification, I have filed a bug [SR-14876] Async let - await - compilation error · Issue #57223 · apple/swift · GitHub