TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Computed property based on contents of array parameter

Forums > SwiftUI

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.

2      

Bump. Anyone? This has to be a simple thing to do ... doesn't it?

2      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.