Search code examples
listforeachswiftuicompletion

Convert a simple list with fetched items to SwiftUI


I am converting a list I have with fetched items thru a completion block to a SwiftUI list. Here is what I am currently working with:

struct MoreView: View {
    
    private let seasonArray = [Season]()
    
    var body: some View {
        List {
            ForEach(seasonArray, id:\.self) { season in
                Text(season.name)
            }
         }
     }

    private mutating func fetchSeasons() {
        ContentManager().getSeasons() { response in
            seasonArray = response.sorted { $0.year < $1.year }
            // Reloaded tableview in UIKit here
        }
    }
}

What is the best practice to populate the list with the seasonArray var after fetchSeasons() runs and returns?


Solution

  • You can set the @State property wrapper for seasonArray and give it an empty default value. When you call the fetchSeasons function it should reload automatically your view without the need to implicitly reload because SwiftUI listens for changes for the seasonArray as an @State property.

    You should instantiate the ContentManager once, as a constant.

    struct MoreView: View {
        
        private let contentManager = ContentManager()
        @State private var seasonArray: [Season] = []
        
        var body: some View {
            List {
                ForEach(seasonArray, id:\.self) { season in
                    Text(season.name)
                }
             }
         }
    
        private func fetchSeasons() {
            contentManager.getSeasons() { response in
                DispatchQueue.main.async {
                    self.seasonArray = response.sorted { $0.year < $1.year }
                    // Reloaded tableview in UIKit here
                }
            }
        }
    }