1

Hello My application fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value error. I learned that there is a problem with options. but I don't know how to change it myself, can you help me?

ref = db.products(category: category.id) this is the place that gives error

import UIKit
import FirebaseFirestore

class ProductsVC: UIViewController, ProductCellDelegate {

    // Outlets
    @IBOutlet weak var tableView: UITableView!
    
    // Variables
    var products = [Product]()
    var category: Category!
    var listener: ListenerRegistration!
    var db : Firestore!
    var showFavorites = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        db = Firestore.firestore()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UINib(nibName: Identifiers.ProductCell, bundle: nil), forCellReuseIdentifier: Identifiers.ProductCell)
        
        setupQuery()
    }
    
    func setupQuery() {
        
        var ref: Query!
        if showFavorites {
            ref = db.collection("users").document(UserService.user.id).collection("favorites")
        } else {
            ref = db.products(category: category.id)
               
        }
        
        listener = ref.addSnapshotListener({ (snap, error) in
            if let error = error {
                debugPrint(error.localizedDescription)
            }
            
            snap?.documentChanges.forEach({ (change) in
                let data = change.document.data()
                let product = Product.init(data: data)
                
                switch change.type {
                case .added:
                    self.onDocumentAdded(change: change, product: product)
                case .modified:
                    self.onDocumentModified(change: change, product: product)
                case .removed:
                    self.onDocumentRemoved(change: change)
                }
            })
        })
    }
zeytin
  • 5,296
  • 4
  • 13
  • 37

1 Answers1

1

To fix unwrapping problem on id then :

if let value = ref {
 value = db.products(category: category.id)
} 
zeytin
  • 5,296
  • 4
  • 13
  • 37