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
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
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 theImage
value is init, it will init aUIImageView
object once. If theImage
value is init again nothing will happen. IfImage
is init with a differentsystemName
param, it will update theUIImageView
object with the new image. Lastly, ifImage
is not init, e.g. as part of anif
clause within body that no longer passes, then theUIImageView
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.