Append items to an array in an object in Swift
15:48 01 Aug 2026

I am trying to append items to an array in Swift.  As long as the array is located inside ContentView this works fine, but if I put the array inside an object, append() no longer works. Here is the ContentView.swift of the first case:

import SwiftUI

struct ContentView: View {
    @State var items: [String] = ["item 1"]
    @State var c: Int = 1
    
    var body: some View {
        VStack {
            List(test.items, id: \.self){
                Text($0)
            }
            Button("Add") {
                c += 1;
                items.append("item " + String(c))
            }
        }
    }
}

#Preview {
    ContentView()
}

When the app stars, “item 1” is displayed, then if I tap “Add”, items 2, 3 etc appear in the list.  This works correctly.

Here is the ContentView.swift of the second case:

import SwiftUI

class TestObject: NSObject {
    @State var items: [String] = ["item 1"]
}

struct ContentView: View {
    private var test = TestObject()
    @State var c: Int = 1
    
    var body: some View {
        VStack {
            List(test.items, id: \.self){
                Text($0)
            }
            Button("Add") {
                c += 1;
                test.items.append("item " + String(c))
            }
        }
    }
}

#Preview {
    ContentView()
}

When the app starts, “item 1” is displayed, but tapping “Add” has no effect.

Why doesn’t append() work?  What is the solution?  I am using Xcode 26 and testing the app on an iPhone with iOS 18.

ios swift swiftui