Understanding SwiftUI View

Why is View a struct and not a class anymore?

Why??

Body of a SwiftUI View

Let us open up the View protocol

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 !!")
}
}
}

What is the some keyword here?

some keyword is to signify that the return type for the computed property is an Opaque Type. Opaque types keep the caller of your property ignorant of the concrete type.

What if you do not want to use some View?

You can also provide a concrete type for the body. No one will say a NO. In our above case, the type of our body is inferred by SwiftUI to be VStack<TupleView<(Text, Text)>>. So if you want your body to have a concrete type, you have to write the type as VStack<TupleView<(Text, Text)>>. But every time you add any other views in your stack, you have to update the type. Isn’t that painful to do?

self is immutable in View body

One of our common requirements is to maintain certain properties in our code as in the below example we have title as one of our dependent properties.

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

How to fix this?

Every mutable source of truth should be marked with @State property.

@State var title: String

What happens if we make SwiftUI view as a class?

If you are as curious as I am, you would have definitely thought about why is SwiftUI view always a struct? Can we not make it a class?

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

What is the above error?

Let us try to reproduce this error by a small understandable example in the playground.

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

You can reach me for any query, feedback, or just want to have a discussion by the following channels:

--

--

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