Swift:在初始化之前使用的常量''

daa*_*aal -1 constants swift swift3

我正试图通过该函数将数据传递给我的第二个VC上的标签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!)")

    }

}
Run Code Online (Sandbox Code Playgroud)

当我设置shopName.text为annotation.title,我得到一个错误说明:

在初始化之前使用常量'destVC'.

我不太清楚出了什么问题.

mli*_*dal 7

您只声明了变量destVC,而没有初始化它.您需要在使用变量之前直接或通过故事板对变量进行实例化,例如:

let destVC = ShopDetailViewController()
Run Code Online (Sandbox Code Playgroud)

要么

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