Understanding SwiftUI View

Why is View a struct and not a class anymore?

Why??

Body of a SwiftUI View

public protocol View {
associatedtype Body : View
var body: Self.Body { get }
}
struct ContentView: View {
var body: some View {
VStack {
Text("Hello Swifty !!")
Text("I am amazing !!")
}
}
}

self is immutable in View body

struct ContentView: View {
var title: String
var body: some View {
VStack {
Button(action: {
self.title = "I am changing this"
}) {
Text("Hit me")
}
}
}
}

Cannot assign to property: ‘self’ is immutable

@State var title: String

What happens if we make SwiftUI view as a class?

class ContentView: View {
var body: some View {
VStack {
Text("")
}
}
}

Protocol ‘View’ requirement ‘_makeView(view:inputs:)’ cannot be satisfied by a non-final class (‘ContentView’) because it uses ‘Self’ in a non-parameter, non-result type position

protocol Producable {
var producedFactory: Factory<Self>? { get }
}
class Factory<T: Producable> {}class PharmacyProduct: Producable {
weak var producedFactory: Factory<PharmacyProduct>? {
nil
}
}
class Paracetamol: PharmacyProduct {}
final class ContentView: View {
var body: some View {
VStack {
Text("")
}
}
}
Crash !!

I would love to hear from you

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store