SwiftUI Programming: Classes and Structs in SwiftUI

Why a class cannot simply replace a struct as a SwiftUI View, what error the compiler gives, and how a final class makes it possible when needed.

Leggi in italiano
Two tilted check mark shaped pipes with their shadows on a yellow wall

I'm pretty sure that everyone had the following question, at least one time.


"If the concept behind a View is the protocol, what if I try to use a class instead?"


Let's try to analyze it in detail.

Swift

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

The code above, although syntactically perfect, produces an error. In fact, the compiler complains that the class itself is too mutable in the course of execution. In fact, a class is indeterminate by its nature: what would happen if ContentView itself had a subclass?

The View protocol would not know how to guarantee uniqueness. * Self * would continue to refer to ContentView and the subclass would violate this rule.

Swift

class SomeView<T: View> {
   var body: some View {
      Text("Hello World")
   }
}

or, simply:

Swift

final class ContentView: View {
   var body: some View {
      Text("Hello World")
   }
}

At this point - if it is really necessary - we can use a class to work in SwiftUI.

Keep reading

All articles
  1. SwiftUI Programming: ObjectBinding and BindableObject
  2. SwiftUI Programming: An Introduction to States
  3. SwiftUI Programming: An Introduction
↑ ↓ navigate↵ openesc close