0

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.

Nirav D
  • 71,513
  • 12
  • 161
  • 183
daanyyaal
  • 301
  • 2
  • 4
  • 16

2 Answers2

8

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
mlidal
  • 1,111
  • 14
  • 27
3

The error is clearly saying that you have not initialized the constant destVC yet and you are trying to use its property shopName. So initializing the destVC before accessing its property will remove the error.

If you are using a storyboard

let destVC = self.storyboard?.instantiateViewController(withIdentifier: "IdentifierOfVC") as! ShopDetailViewController

If you are using an xib

let destVC = ShopDetailViewController()
Alex Zavatone
  • 4,106
  • 36
  • 54
Nirav D
  • 71,513
  • 12
  • 161
  • 183
  • wouldn't `let destVC : ShopDetailViewController` be initializing it? How else would I initialize it? – daanyyaal Dec 21 '16 at 13:03
  • @daanyyaal If you doesn't know how to set identifier of viewController in storyboard check this so answer http://stackoverflow.com/a/15478575/6433023 – Nirav D Dec 21 '16 at 13:05