---
title: "SwiftUI Programming: Classes and Structs in SwiftUI"
url: https://www.sofapps.it/blog/swiftui-programming-classes-structs/
date: 2020-01-07
author: Costantino Pistagna
language: en
tags: [SwiftUI, Tutorial]
---

# SwiftUI Programming: Classes and Structs in SwiftUI

> Declaring a View as a plain class does not work, because a class can have subclasses and the View protocol could not guarantee uniqueness of Self. Marking the class final removes the problem. A class can then be used in SwiftUI when it is really needed.

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

<hr>

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

<hr>

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.
