skip to Main Content

In SwiftUI, if we have a let that is declared inside the View body code such as:

var body: some View {

    // ...

    let settingsBar = ZStack{
                        Image(systemName: "gear")
                            .resizable()
                            .scaledToFit()
                            .frame(width:buttonCircleSide/2,height:buttonCircleSide/2)
                            .foregroundStyle(.white)
                    }.frame(width: buttonCircleSide, height: buttonCircleSide)

    // ...

}

Is that optimized somehow either by the compiler or something else so that this object creation doesn’t actually happen every time the view is refreshed? Or do we need to move it higher in scope? Is it not actually a "real" assignment operation?

2

Answers


  1. SwiftUI views are declarative, meaning that we can only declare how our view should be. let cannot be used here
    It is not imperative like the UIKit where the objects are created manually.

    Whether the view needs to be redrawn or not is checked by swiftUI runtime and that can depend on multiple things like position change or change in any of the view dependencies or changes in property wrapper values like @State or @ObservedObject etc

    Login or Signup to reply.
  2. Doing Image(systemName: "gear") just creates a struct value on the memory stack, it is negligible to create these values multiple times. You are right that SwiftUI does to an optimization, i.e. after the first time the Image value is init, it will init a UIImageView object once. If the Image value is init again nothing will happen. If Image is init with a different systemName param, it will update the UIImageView object with the new image. Lastly, if Image is not init, e.g. as part of an if clause within body that no longer passes, then the UIImageView object will be deinit and its memory freed up.

    You can think of SwiftUI View structs like view model data descriptions for how UI objects should be init, update and deinit. It chooses the most suitable UI objects for the current context and platform.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search