amirbt17
amirbt17

Reputation: 611

App Started Crashing When Adding New Document to Firestore (Continued Crashing Even After Document Was Deleted)

This is my relevant struct:

struct MealPlan {
    
    var docID:String?
    var title:String?
    var ingredientsProduce:[String]?
    var ingredientsProtein:[String]?
    var ingredientsSpices:[String]?
    var ingredientsOther:[String]?
    var isStarred:Bool?
    
}

And this is my model:

class MealPlanModel {
    
    var delegate:MealPlanProtocol?
    var listener:ListenerRegistration?
    
    func getMealPlans(_ starredOnly:Bool = false) {
        
        // Detach any listener
        listener?.remove()
        
        // Get a reference to the database
        let db = Firestore.firestore()
        
        var query:Query = db.collection("mealPlans")
        
        // If filtering for starred Meal Plans, update the query
        if starredOnly {
            query = query.whereField("isStarred", isEqualTo: true)
        }
        
        self.listener = query.addSnapshotListener({ (snapshot, error) in
            
            // Check for errors
            if error == nil && snapshot != nil {
                
                var mealPlans = [MealPlan]()
                
                // Parse documents into mealPlans
                for doc in snapshot!.documents {
                    
                    let m = MealPlan(docID: doc["docID"] as! String, title: doc["title"] as! String, ingredientsProduce: doc["ingredientsProduce"] as! [String], ingredientsProtein: doc["ingredientsProtein"] as! [String], ingredientsSpices: doc["ingredientsSpices"] as! [String], ingredientsOther: doc["ingredientsOther"] as! [String], isStarred: doc["isStarred"] as! Bool)
                    
                    mealPlans.append(m)
                    
                }
                
                // Call the delegate and pass back the notes in the main thread
                DispatchQueue.main.async {
                    self.delegate?.mealPlansRetrieved(mealPlans: mealPlans)
                }
                
                
            }
            
        })

This is what I can't figure out:

  1. My project was building fine with this code
  2. Then I added a new document in Firestore with the same keys
  3. App started crashing
  4. I deleted that document from Firestore (so going back to where I was at (1) when it worked) and the project continued to crash

The error I'm getting is: Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value. The error is marked at ingredientsProduce: doc["ingredientsProduce"] as! [String] from my code above.

I couldn't find any typos and the keys all have values in Firestore. Also, everything was working fine before I added/deleted the new document, so it seems like nothing has changed since it last worked. I cleared my build folder and quit/reopened Xcode as well.

Anyone know what might be happening?

Upvotes: 0

Views: 98

Answers (1)

andromedainiative
andromedainiative

Reputation: 4962

Well you are force unwrapping an optional value hence your app is crashing when it turns out to be nil.

doc["ingredientsProduce"] as! [String] // as! means force cast it to array of strings in your example

If the value of ingredientsProduce is an optional you can't force unwrap it and expect it not to crash when it's nil.

Example of safe unwrapping

if let myValues = doc["ingredientsProduce"] as? [String] {
    // safe to use myValues
    _ = myValues.map { print($0) }
}

Upvotes: 1

Related Questions