2

I want to change name right after I get User(). DidSet does not work here. is there an alternative for didSet in SwiftUI?

struct Person: Identifiable {
let id = UUID()
var name: String
var number: Int
}

class User: ObservableObject {
@Published var array = [Person(name: "Nick", number: 3),
                        Person(name: "John", number: 2)
]
}

struct ContentView: View {

@ObservedObject var user = User() {
    didSet {
        user.array[0].name = "LoL"
    }
}

var body: some View {
    VStack {
        ForEach (user.array) { row in
            Text(row.name)
        }
    }
}
}

1 Answers1

0

If I correctly understood your expectation (having your code) there are couple of options to reach the goal:

Option 1: Set up created user in init (as properties created before init)

init() {
    self.user.array[0].name = "LoL"
}

Option 2: Set up it on view appearance

VStack {
    ForEach (user.array) { row in
        Text(row.name)
    }
}
.onAppear {
    self.user.array[0].name = "LoL"
}
Asperi
  • 228,894
  • 20
  • 464
  • 690