Skip to main content

Command Palette

Search for a command to run...

UIViewRepresentables must be value types

Updated
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.

I
Igor2y ago

And yet you write “Code using a struct conforming to View will compile but will cause a runtime exception…” ))

M

Thanks for pointing out my mistake. I corrected the text and wrote "Code using a spinal class conforming to View will compile but will cause a runtime exception…"

1
I
Igor2y ago

Marco Eidinger could you please clarify what “spinal class” means?

M

Igor final class

More from this blog

Dev blog post potpourri by senior software engineer Marco Eidinger

149 posts

Hello 👋🏻 , I am a Software Engineer working on open source and enterprise mobile SDKs for iOS and MacOS developers written in Swift. From 🇩🇪 and happily living in 🇺🇸