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

struct contentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

To make the starting point as Struct all the UI which we will design on view will be inside the Struct and we know Struct is value type and it will allocate memory in the stack.

How it will impact as far as memory is a concern?

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
Ashwinkumar Mangrulkar
  • 2,956
  • 3
  • 15
  • 17
  • You have asked two questions: "What is the benefit to make starting point Struct and not Class in SwiftUI?" and "How it will impact as far as memory is a concern?". Pick one. – Sweeper Jul 17 '19 at 07:28
  • you can check the answer here: https://stackoverflow.com/questions/24232799/why-choose-struct-over-class – Ben Shabat Jul 17 '19 at 07:32

1 Answers1

10

The value-type behavior is what they actually want in SwiftUI. One of the inspiration for SwiftUI was the virtual DOM in ReactJS.

The crucial part of the implementation is the fact that there are multiple copies of the UI tree and SwiftUI compares them to see what has changed. For example:

  1. Generate view tree A
  2. Render view tree A to screen
  3. State changes (e.g. user has clicked a button)
  4. Generate view tree B
  5. Check differences between tree A and B and render only what is required.

Generating copies is rather difficult with classes but it's simple with value types.

There are additional advantages when comparing against classes but this is the main reason. Value types (as immutable data structures) are perfect for functional programming patterns used within SwiftUI.

Regarding memory, note that structs do not occupy more space than classes and it is a misconception that they live only in the stack. They are allocated as temporaries in the stack, but once you save them somewhere (e.g. to a class property), they don't live in the stack any more.

Sulthan
  • 128,090
  • 22
  • 218
  • 270