Class and Struct in SwiftUI


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

I'm sure the question above will have arisen to all the most curious. 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.

© Copyright 2019 Sofapps - All Rights Reserved - VAT 05197020877