[SOLVED] Map array to be conform with a Model in MVVM structure Swift

Issue

I fetch data from Firebase and in this data I have an array of dictionary.

I need to set this array of dictionary in days conform to StickModel because the key days in HabitModel need to be conform with [StickModel].

But I get this error :

Error

I use MVVM structure.

import Foundation
import Firebase

class HabitsViewModel: ObservableObject {
    @Published var habites = [HabitModel]()
    @Published var days = [StickModel]()
    
    private var db = Firestore.firestore()
    
    func fetchData() {
        debugPrint("Fetch Data...")
        db.collection("users/" + (Auth.auth().currentUser?.uid)! + "/Habits").addSnapshotListener { (querySnapshot, error) in
            guard let documents = querySnapshot?.documents else {
                debugPrint("No document")
                return
            }
            
            self.habites = documents.map { queryDocumentSnapshot -> HabitModel in
                let data = queryDocumentSnapshot.data()
                let id = queryDocumentSnapshot.documentID
                let title = data["title"] as? String ?? ""
                let progress = data["progress"] as? Float ?? 0
                let start = data["start"] as? String ?? ""
                let end = data["end"] as? String ?? ""
                
                                
                self.days = data["days"].map { myday -> StickModel in
                    
                    let completed = myday["completed"] as? Bool ?? false
                    let dayLetter = myday["day"] as? String ?? ""
                    let progress = myday["progress"] as? Float ?? 0
                    
                    return StickModel(id: UUID().uuidString, progress: progress, completed: completed, day: dayLetter)
                }
                
                
                return HabitModel(id: id, title: title, progress: progress, start: start, end: end, days: self.days)
            }
        }
    }
}

Solution

Try this:

self.days = (data["days"] as? [[String: Any]] ?? []).map -> StickModel in

Answered By – NoeOnJupiter

Answer Checked By – Terry (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.