UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Unable to view items in List after ObservedObject array

Forums > SwiftUI

This is my List:

List(0..<viewModel.databases.count) { item in
    Text("item \(self.viewModel.databases[item].name)")
}

When I print(viewModel.databases.count) I am getting 4, which is right, but unable to display in List.

When button is clicked I am appending 4 items:

Button("Test") {
    let db: Database = Database()
    db.name = "test"
    var newDBS: [Database] = []
    newDBS.append(db)
    newDBS.append(db)
    newDBS.append(db)
    newDBS.append(db)
    self.viewModel.databases = newDBS
}

And this is my observable:

import Combine

class DatabaseObservable: ObservableObject {
    var objectWillChange = PassthroughSubject<Void, Never>()

    init() {
        databases = []
    }

    @Published var databases: [Database] = [] {
        didSet {
            objectWillChange.send()
        }
    }
}

2      

hi,

i'm inferring that your view model keeps a list of databases, and you want to list those databases by name. the following seems to do it, without explicitly resorting to supplying a lot of code from Combine. i've also added a few things to your viewModel to make the ContentView code a little easier; and the button adds just one database at a time.

import SwiftUI

class Database {
    var name: String = ""
}

class ViewModel: ObservableObject {
    @Published var databases: [Database] = []

    var databaseCount: Int { databases.count }

    func name(at index: Int) -> String {
        return databases[index].name
    }

    func append(database: Database) {
        databases.append(database)
    }
}

struct ContentView: View {

    @ObservedObject var viewModel: ViewModel = ViewModel()

    var body: some View {
        VStack {
            Button("Add a new database") {
                let db = Database()
                db.name = "test"
                self.viewModel.append(database: db)
            }

            Text("Database count is \(viewModel.databaseCount)")

            List(0..<viewModel.databaseCount, id: \.self) { index in
                Text("item \(self.viewModel.name(at: index))")
            }

        }
    }
}

hope that helps,

DMG

2      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.