Using Swift withCheckedThrowingContinuation in methods without return value

When refactoring old closure-based code to new Swift concurrency it is inevitable that you come accross scenario where you need to call withCheckedThrowingContinuation where enclosing method has no return value. In that case, you should get error in Xcode: Generic parameter ’T’ could not be inferred

Let’s consider the following block of code

func fetchData() async throws {
    try await withCheckedThrowingContinuation({ continuation in
        URLSession.shared.dataTask(with: URL(string: "https://example.com")!) { data, response, error in
            if let error = error {
                continuation.resume(throwing: error)
                return
            }
            continuation.resume()
        }.resume()
    })
}

This code produces the error above because withCheckedThrowingContinuation method has generic parameter which compiler usuallly infers from return value of enclosing method. However, our enclosing method fetchData has no return value thus compiler raises the error.

Fortunately the fix is incredibly simple, just cast return type to Void

func fetchData() async throws {
    try await withCheckedThrowingContinuation({ continuation in
        URLSession.shared.dataTask(with: URL(string: "https://example.com")!) { data, response, error in
            if let error = error {
                continuation.resume(throwing: error)
                return
            }
            continuation.resume()
        }.resume()
    }) as Void
}

It is important to note that this approach works for all methods not just for withCheckedThrowingContinuation or other methods specific to Swift concurrency.

How to check if Xcode is building for previews

Lately, I find myself often dealing with a lot of Xcode build phases. One common problem that I encounter is that SwiftUI previews won’t work if some build phase runs a script which messes with Xcode project file or with individual files. For example, script which sorts files alphabetically may modify Xcode project file which will prevent previews to work. To work around this problem, you can check if Xcode is building for previews and then decide whether to run the script or not.

if [ ${ENABLE_PREVIEWS} == NO ];
then
echo "Running sorting script"
fi

I have spent some time playing with Apple’s Multi Peer connectivity framework on iOS. It is incredible what kind of apps it enables. Here is my unfinished sample app that allows for voice calls in cases where there is no internet access or even infrastructure Wi-Fi. I have to say that most difficult part was configuring AVAudioEngine it is extremely easy to mess things up. Audio is hard.