@StateObject Property Wrapper in SwiftUI

Michael Chan
1 min readJul 1, 2020

Looking at the Playground code above, you can see 2 steppers which behaves like this.

DoubleStepperView behaviour before using @StateObject

OuterStepperView counter gets reset everything time the top stepper is tapped on. If you wanted OuterStepperView counter to be independent from the top stepper, the only other solution to solve this would be to inject the Count object into OuterStepperView.

Doing that doesn’t always make sense because the OuterStepperView is constantly recreated when TwoStepperView is invalidated, meaning that Count object in OuterStepperView loses it’s state and constantly recreated. This could be expensive if Count created more expensive objects. Another reason why injecting Count to OuterStepperView might not be the correct solution could be that the Count is a private class within a framework or file and so it might not be possible to do that.

@StateObject is a Property Wrapper in SwiftUI(as of WWDC 2020). The @StateObject behaves in a similar fashion to @ObservedObject Property Wrapper, but with 1 key difference. A @StateObject property does not get recreated constantly if the View, it is declared in, is invalidated.

In our example, if we replace the @ObservedObject for the property counter in OuterStepperView to a @StateObject. This follow happens.

DoubleStepperView behaviour using @StateObject

--

--