SwiftUI Programming: Classes and Structs in SwiftUI

Jan 07, 2020 · 1 min read · Costantino Pistagna · @valv0

SwiftUI Programming: Classes and Structs in SwiftUI

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.



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.


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

or, simply:


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.


Costantino Pistagna
Costantino Pistagna · @valv0 Costantino is a software architect, project manager and consultant with more than ten years of experience in the software industry. He developed and managed projects for universities, medium-sized companies, multi-national corporations, and startups. He is among the first teachers for the Apple's iOS Developer Academy, based in Europe. Regularly, he lectures iOS development around the world, giving students the skills to develop their own high quality apps. While not writing apps, Costantino improves his chefs skills, travelling the world with his beautiful family.