SwiftUI preview Crash when using tasks on a view (when supporting iOS 14)

Hello, I encountered something that seems like a bug in XCode/Swift that's easy to reproduce:

in a swift Package, depending on the supported platform, I get a crash upon tapping the button in a preview. iOS 14 -> Crash iOS 15 + -> No issue

here is the package.swift for repro

import PackageDescription
let package = Package(
    name: "PreviewCrashDemo",
    platforms: [.iOS(.v14)], // Changing this to iOS 15 fixes the crash ><
    products: [
        .library(
            name: "PreviewCrashDemo",
            targets: ["PreviewCrashDemo"]),
    ],
    dependencies: [],
    targets: [
        .target(
            name: "PreviewCrashDemo",
            dependencies: []),
    ]
)

And here is the code for my preview:

struct Test_Previews: PreviewProvider {
    static var previews: some View {
        Button("Hello world") {
                Task {
                    print("Hi!")
                }
            }
            .previewDisplayName("Crash on iOS 14")
    }
}
Answered by HugoSay in 745154022

Great news, It looks like issue is fixed on XCode 14.3 ! :D

Hi,

Sorry to hear you are having problems getting previews working. I believe this is known issue related to usage of swift concurrency in an app that also back deploys to an older release.

Does the issue go away if you remove the usage of Task? If so then this is something we are hoping to fix in a future release.

Hey,

It goes away, but I cannot do async work when tapping the button. (The real-world application is to call an async func at this point)

Does that mean it is impossible to use async functions pre-iOS 15 in swiftUI ?

Accepted Answer

Great news, It looks like issue is fixed on XCode 14.3 ! :D

SwiftUI preview Crash when using tasks on a view (when supporting iOS 14)
 
 
Q