-3

I keep getting:

Initializer for conditional binding must have Optional type, not 'Dealership'

What would I do to resolve this issue occurring in my code? My Xcode version is 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()

        }
    }
rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Please [search on the error](https://stackoverflow.com/search?q=%5Bswift%5D+Initializer+for+conditional+binding+must+have+Optional+type%2C+not) before posting. This has been asked and answered many times before. – rmaddy Apr 23 '19 at 03:39

1 Answers1

0

Please post which line this is actually failing on. Now my guess is its

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

This won’t fail to instantiate because all the fields are force unwrapped and I’m guessing Dealership doesn’t have an optional init in it either. So remove the if from the if let because you can’t unwrap a value that won’t ever be optional in Swift.

Justin
  • 1,318
  • 9
  • 12