daanyyaal
daanyyaal

Reputation: 301

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.

Upvotes: 0

Views: 21643

Answers (2)

Nirav D
Nirav D

Reputation: 72410

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

Upvotes: 3

mlidal
mlidal

Reputation: 1153

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

Upvotes: 8

Related Questions