SwiftUI Preview crash with await async iOS15 if returns a struct with UUID

Viewed 530

I reduced to very simple code. If the struct has a Int is working, if there is an UUID the preview is crashing (it's working if I run on the simulator or real device)

Tested with iOS 15 Xcode 13.1 and beta 13.2

import SwiftUI
import Combine

struct MyStruct: Codable, Hashable, Identifiable {
    var id: UUID = UUID() //with Int is ok
    var str: String
}

struct ContentView2: View {
    
    @State private var myStruct: MyStruct = MyStruct(str: "struct1-init")
    
    var body: some View {
        VStack {
            Text(myStruct.str)
                .onAppear(perform: doSometingStruct)
        }
    }
    
    private func doSometingStruct() {
        Task {
            let get = await getAsyncStruct()
            myStruct = get
        }
    }
    
    private func getAsyncStruct() async -> MyStruct {
        let str = MyStruct(str: "struct1-done")
        return str
    }
}

struct ContentView2_Previews: PreviewProvider {
    static var previews: some View {
        ContentView2()
    }
}
3 Answers

It seems to be a bug of xcode to preview Views with async-code... Try to test with commented Task:

private func doSometingStruct() {
        //Task {
        //    let get = await getAsyncStruct()
        //    myStruct = get
        //}
    }

Doesn’t feel “right”, but was able to get around the issue by not having the async function return anything and store the struct in a global variable that can be gotten from the calling function. Feels all sorts of wrong but it does work to fix the crash. If someone has a better solution, I’d love to know!

This appears to be fixed in Xcode 14.0

Related