Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a class be a View in SwiftUI?

Tags:

swiftui

I can define something like

struct SimpleView: View { ...

but something like

final class SimpleView: View { ...

does crash with EXC_BAD_INSTRUCTION during runtime. Is is impossible in general or just in my case?

like image 843
georgij Avatar asked Feb 20 '20 13:02

georgij


People also ask

Why does SwiftUI use structs instead of classes?

First, there is an element of performance: structs are simpler and faster than classes. I say an element of performance because lots of people think this is the primary reason SwiftUI uses structs, when really it's just one part of the bigger picture.

What is a view in SwiftUI?

The SwiftUI framework defines a broad range of primitive views. Text , for example, doesn't return a view. It draws the string it is given to the screen. Those primitive views are the building blocks you can use in the custom views you create to build your application's user interface.

What is a class in SwiftUI?

Classes Are Reference Types. Unlike value types, reference types are not copied when they're assigned to a variable or constant, or when they're passed to a function. Rather than a copy, a reference to the same existing instance is used.

How do I create a view in SwiftUI?

To get started, you'll create a new custom view to manage your map. Choose File > New > File, select iOS as the platform, select the “SwiftUI View” template, and click Next. Name the new file MapView. swift and click Create.


1 Answers

The short answer: no.


The longer answer is that Swift (the language) allows it, as there is no way to prohibit a protocol from being adopted by classes (although you can force a protocol to be adopted by only classes, that's the opposite of what would be needed). However, SwiftUI relies on views being structs for its internal methods of updating views, so no. This is related to why you need to use @State for value types (because it observes when the value changes, and if a reference type was used, the view would only be updated when the object is reassigned, not when any properties change) and use @ObservedObject for reference types (and ObservableObjects need to be classes.

like image 123
Sam Avatar answered Oct 08 '22 20:10

Sam