How to Append Items to an Array Inside an Object in SwiftUI
If you are building a SwiftUI application and notice that appending items to an array works perfectly when declared directly inside a struct View, but fails to update the UI when the array lives inside a custom class object, you are not alone. This is one of the most common state management issues developers face in SwiftUI.
Why Doesn't append() Work Inside a Class?
In your original code, the array actually is receiving the new items in memory when you call test.items.append(...). The reason your UI does not update is that SwiftUI has no way of knowing the data changed, so it skips redrawing the view.
This happens due to two fundamental rules of SwiftUI state management:
@Stateis designed for View structs: Placing the@Stateproperty wrapper inside a standard reference type (aclass) does not work. SwiftUI's@Statemechanism is built specifically to manage primitive values or value types directly owned by a View struct lifecycle.- Reference types don't trigger automatic updates: Classes are reference types. When you mutate a property inside a class (like appending an element to an array), the reference to the class instance itself remains unchanged. SwiftUI cannot detect internal mutations of standard class instances without explicit observation frameworks.
Solution 1: The Modern Approach (iOS 17+ & Swift 5.9+)
If you are targeting modern iOS versions (iOS 17 and later), Apple introduced the Observation framework using the @Observable macro. This is the recommended approach for state management in modern Swift.
To fix the issue, remove @State from inside the class, mark the class with @Observable, and store the class instance in your view using @State: