Search code examples
swiftswift3constants

Swift: Constant ' ' used before being initialized


I'm attempting to pass data to a label on my second VC through the function func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView).

func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {

    print("Annotation selected")


    if let annotation = view.annotation as? POIAnnotations {

       let destVC : ShopDetailViewController

        destVC.shopName.text = annotation.title!

        print("Your annotation title is: \(annotation.title!)")

    }

}

When I set shopName.text to annotation.title, I get an error stating:

Constant 'destVC' used before being initialized.

I'm not quite sure what's going wrong.


Solution

  • You have only declared the variable destVC, not initialized it. You need to instansiate the variable, either directly or through the storyboard before using it, e.g. this:

    let destVC = ShopDetailViewController()
    

    or

    let storyboard = UIStoryboard(name: "MyStoryboardName", bundle: nil)
    let destVC = storyboard.instantiateViewController(withIdentifier: "ShopDetailViewController") as! ShopDetailViewController