Can we use @State with C++ structs

Hi,

Is it supported to use a C++ struct as a state variable in a SwiftUI view?

@State private var myCppStruct = MyCppStruct()

I'm seeing some crashes when I use one of my structs like this within a SwiftUI view, then type into an unrelated edit field in that view.

My MyCppStruct has pod members, nested structs, std::string members, std::vector (of the nested struct), but other than that pretty standard (no pointers or class type members anywhere). I can use MyCppStruct extensively elsewhere (without the @State) in my swift code without issue.

State shouldn't have any impact on C++ structs. All @State does is make sure the item is reused when the view is reinitialized. What crash are you getting?

I would expect this to only be true of actually POD structures and classes. SwiftUI uses a bunch of different sources of identity to compare values, but fundamentally falls back to a memcmp which will absolutely not behave properly for most non-POD types. The other thing I'd worry about is the backing storage for an @State variable copying a non-trivial C++ type. I'm not sure if Swift's smarts win out over SwiftUI's smarts in that case. If the latter is true, I would be worried about a non-trivial type having essentially a memcpy performed instead of e.g. dispatching through its copy constructor.

Basically, I think @avoirtech it's worth trying this out with a proper POD type and making sure things work fine - which they should as C structs should work fine in this position too - then filing a radar describing your non-POD type.