Just learning Swift, so I'm sure I'm missing something basic here...
I have a pretty basic data class:
class Peripheral : Identifiable, ObservableObject {
init(id: UUID, name: String, isConnected: Bool = false) {
self.id = id
self.name = name
self.isConnected = isConnected
}
let id: UUID
let name: String
@Published var isConnected: Bool = false
}
In a View that receives a Peripheral
as a parameter, updates to isConnected
are seen immediately, as expected:
struct PeripheralSelectionCard: View {
@ObservedObject var peripheral: Peripheral
var body: some View {
if (peripheral.isConnected) {
Button(action: onDisconnect) {
Text("Disconnect")
}
} else {
Button(action: onConnect) {
Text("Connect")
}
}
}
}
}
However, in another view that receives an array of Peripheral objects, I can't seem to make a computed property that depends on the array contents update:
struct ConfigureBluetoothViewBody: View {
var peripherals: [Peripheral]
// This will always remain false
var canContinue: Bool {
peripherals.contains { p in p.isConnected }
}
var body: some View {
VStack {
Button(action: { print("go") }) {
Text("Continue")
}
.disabled(!canContinue)
ForEach(peripherals) { peripheral in
PeripheralSelectionCard(
peripheral: peripheral,
)
}
}
}
}
I think I fundamentally understand why ... the view is only aware of updates to the array itself (insert, remove, etc.) and that is working fine. But it is not aware whenever an update occurs to a property within the array. What's the recommended way to work with this scenario? This seems like it would be very very common.