【问题标题】:I get a Error, but on other models it is working我得到一个错误,但在其他模型上它正在工作
【发布时间】:2022-08-18 20:33:27
【问题描述】:

我使用与其他模型大致相同的 ViewModel。 但是在这个我得到一些错误几乎都是“自我”错误。 我找不到它来自哪里。

请参阅此处的错误:

这是我的代码:

//

导入 SwiftUI 导入 Firebase 进口组合

类 RouteViewModel: ObservableObject {

// MARK: Filtered Array
@Published var myRoutes: [Route]?
// MARK: Raw All Notes
@Published var allRoutes: [Route]?

// MARK: Search Text
@Published var searchText: String = \"\"
// Combine Search
var cancellable: AnyCancellable? = nil

// MARK: New Note
@Published var showAddRoutePopup: Bool = false
@Published var boxNumberIdentificatie: [String]
@Published var dateBringDate: Date
@Published var customerIdentificatie: String = \"\"
@Published var locationPlaceLogLat: GeoPoint

// MARK: Alert
@Published var showAlert: Bool = false
@Published var alertMsg: String = \"\"

// MARK: Edit Note
@Published var editRoute: Route?

// MARK: Log Status
@AppStorage(\"log_status\") var log_status: Bool = false
// MARK: Logout Alert
@Published var showLogoutPopup: Bool = false

init(){
    fetchRoutes()
    
    // Combine Search
    cancellable = $searchText.removeDuplicates()
        .debounce(for: 0.5, scheduler: RunLoop.main)
        .sink(receiveValue: { string in
            if string != \"\"{
                self.filterRoutes(searchText: string)
            }
            else{
                withAnimation{
                    self.myRoutes = self.allRoutes
                }
            }
        })
}

// MARK: Fetching Notes
func fetchRoutes(){
    
    guard let uid = Auth.auth().currentUser?.uid else{
        log_status = false
        return
    }
    
    let routesRef = Firestore.firestore().collection(\"Routes\")
    
    routesRef.order(by: \"lastModified\", descending: true).addSnapshotListener { snapshot, err in
        guard let docs = snapshot?.documentChanges else{
            return
        }
        
        DispatchQueue.main.async {[self] in
            
            if allRoutes == nil{allRoutes = []}
            docs.forEach { doc in
                if let route = try? doc.document.data(as: Route.self){
                 
                    switch doc.type{
                    case .added: allRoutes?.append(route)
                    case .modified: updateRoute(route: route)
                    case .removed: removeRoute(route: route)
                    }
                }
            }
            sortRoutes()
        }
    }
}

func sortRoutes(){
    
    DispatchQueue.global(qos: .userInteractive).async {
        let sorted = self.allRoutes?.sorted(by: { first, second in
            return second.dateAdd < first.dateAdd
        })
        
        DispatchQueue.main.async {[self] in
            allRoutes = sorted
            withAnimation(myRoutes == nil ? .none : .default){
                myRoutes = allRoutes
            }
        }
    }
}

func filterRoutes(searchText: String){
    
    DispatchQueue.global(qos: .userInteractive).async {
        let filtered = self.allRoutes?.filter({ route in
            
            return route.customerId.lowercased().contains(searchText.lowercased())
            
        })
        
        DispatchQueue.main.async {
            withAnimation{
                self.myRoutes = filtered
            }
        }
    }
}

func addRoute(){
    
    withAnimation{
        showAddRoutePopup = false
    }
    if customerIdentificatie == \"\"{return}
    
    let routesRef = Firestore.firestore().collection(\"Routes\")
    
    if let editRoute = editRoute {
        
        routesRef.document(editRoute.id ?? \"\").updateData([
            \"boxId\": boxNumberIdentificatie,
            \"dateBring\": dateBringDate,
            \"customerId\": customerIdentificatie,
            \"locationPlace\": locationPlaceLogLat
        ])
        clearData()
        return
    }
    
    let route = Route(boxId: boxNumberIdentificatie, dateAdd: Date(), dateBring: dateBringDate, customerId: customerIdentificatie, locationPlace: locationPlaceLogLat)
    
    do{
        let _ = try routesRef.addDocument(from: route)
        clearData()
    }
    catch{
        clearData()
        alertMsg = error.localizedDescription
        showAlert.toggle()
    }
}

func updateRoute(route: Route){
    if let index = myRoutes?.firstIndex(where: { currentRoute in
        return currentRoute.id == route.id
    }){
        allRoutes![index] = route
    }
}

func removeRoute(route: Route){
    if let index = myRoutes?.firstIndex(where: { currentRoute in
        return currentRoute.id == route.id
    }){
        allRoutes?.remove(at: index)
    }
}

func deleteRoute(){
    guard let editRoute = editRoute else {
        return
    }
    
    let routesRef = Firestore.firestore().collection(\"Routes\")
    
    routesRef.document(editRoute.id ?? \"\").delete()
    withAnimation{
        showAddRoutePopup = false
    }
    clearData()
}

func clearData(){
    boxNumberIdentificatie = [\"\"]
    dateBringDate = Date()
    customerIdentificatie = \"\"
    editRoute = nil
}

}

我希望有人看到我没有看到的问题。 非常感谢.. :)

  • 请分享更多详细信息,例如文本形式的错误消息以及您尝试解决这些错误的尝试
  • 你必须在做任何事情之前初始化你的变量,比如 boxNumberIdentificatie, dateBringDate locationPlaceLogLat

标签: swift swiftui


【解决方案1】:

您的某些属性——dateBringDatelocationPlaceLogLat——没有默认值,因此在您在init 方法中调用fetchRoutes 时未初始化。要修复,您应该在 init 的开头初始化它们或提供默认值:

@Published var dateBringDate: Date = Date()

基本上,问题在于 Swift 要求您在调用该对象的任何方法之前初始化该对象的属性。例如,如果fetchRoutes 试图访问dateBringDate 的值,该规则可以防止出现错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-06
    • 1970-01-01
    • 2020-05-14
    • 1970-01-01
    • 2020-11-10
    • 2021-02-04
    • 2017-03-12
    • 1970-01-01
    相关资源
    最近更新 更多