UIViewRepresentables must be value types

Β·

1 min read

At work, I inherited some SwiftUI code to maintain. The following code is simplified.

final class MySwiftUIViewWrappingUIView: UIViewRepresentable {
    // ...
}

The existing code works fine running on iOS 15. But running the same code on iOS 16 will lead to a runtime exception. Surprise πŸ’£

Fatal error: UIViewRepresentables must be value types: MySwiftUIViewWrappingUIView

Apparently, the Apple team decided to align the behavior with types directly conforming to SwiftUI's View protocol. Code using a final class conforming to View will compile but will cause a runtime exception on iOS 15 and iOS 16.

We should all listen to Paul Hudson when he talks about Why does SwiftUI use structs for views?

If you use a class for your view you might find your code either doesn’t compile or crashes at runtime. Trust me on this: use a struct.

The solution to the encountered problem above is simple.

struct MySwiftUIViewWrappingUIView: UIViewRepresentable {
    // ...
}

I wish I knew why my colleague chose a final class πŸ€”

Anyway, the key takeaway is that you must use a value type (struct or enum) for your SwiftUI Views and UIViewRepresentables.