【问题标题】:My Swift App gave an Error but I don't know how to Fix it? Can you help me? [duplicate]我的 Swift 应用程序出错但我不知道如何修复它?你能帮助我吗? [复制]
【发布时间】:2020-10-31 14:32:16
【问题描述】:

您好,我的应用程序致命错误:在隐式展开可选值错误时意外发现 nil。我了解到选项存在问题。但是我自己不知道怎么改,你能帮我吗?

ref = db.products(category: category.id)这是报错的地方

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)
                }
            })
        })
    }

【问题讨论】:

  • 您的category 似乎未初始化。
  • 但是 xcode 指向 id。
  • 在运行时编码和记录时跳转到定义是不同的。

标签: objective-c swift swift3 swiftui


【解决方案1】:

然后解决 id 上的展开问题:

if let value = ref {
 value = db.products(category: category.id)
} 

【讨论】:

  • 是的代码修复了错误,但在底部 ref.addSnapshotListener 位置再次出现了相同的错误
  • var ref: 查询?使其成为全局变量,如果让检查所有引用,则执行相同操作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多