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?
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.
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.
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.
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.
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 ObservableObject
s need to be class
es.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With