条件绑定的初始化程序必须具有Optional类型,而不是'Dealership'

时间:2019-04-23 03:25:53

标签: ios swift

我不断得到:

  

用于条件绑定的Initializer必须具有可选类型,而不是'Dealership'

该如何解决代码中出现的此问题?我的Xcode版本是10.1。

import UIKit
import FirebaseCore
import FirebaseFirestore
import SDWebImage

class TableViewController: UITableViewController {

    private var documents: [DocumentSnapshot] = []
    public var dealerships: [Dealership] = []
    private var listener : ListenerRegistration!
    var selectedDealership: Dealership? = nil

    fileprivate func baseQuery() -> Query {
        return Firestore.firestore().collection("dealerships").limit(to: 50)
    }

    fileprivate var query: Query? {
        didSet {
            if let listener = listener {
                listener.remove()
            }
        }
    }

    override func viewDidAppear(_ animated: Bool) {
        self.dealerships = []

        self.listener =  query?.addSnapshotListener { (documents, error) in
            guard let snapshot = documents else {
                print("Error fetching documents results: \(error!)")
                return
            }

            for snap in snapshot.documents {
                // Error on the following line
                if let dealership = Dealership(name: snap.data()["name"] as! String, location: snap.data()["location"] as! String, opening_times: snap.data()["opening_times"] as! String, image_url: snap.data()["image_url"] as! String, maps_link: snap.data()["maps_link"] as! String, phone: snap.data()["phone"] as! String, id: snap.data()["name"] as! String){
                    self.dealerships.append(dealership)
                }
            }

            //self.dealerships = results
            self.documents = snapshot.documents
            self.tableView.reloadData()

        }
    }

1 个答案:

答案 0 :(得分:0)

请发布这实际上是哪一行失败。现在我的猜测是

if let dealership = Dealership(name: snap.data()["name"] as! String, location: snap.data()["location"] as! String, opening_times: snap.data()["opening_times"] as! String, image_url: snap.data()["image_url"] as! String, maps_link: snap.data()["maps_link"] as! String, phone: snap.data()["phone"] as! String, id: snap.data()["name"] as! String){
                self.dealerships.append(dealership)
}

这不会实例化,因为所有字段都是强制展开的,而且我想Dealership也没有可选的init。因此,请从if let中删除if,因为您无法解开Swift中永远不会选择的值。