Swift 使用两个函数将注释添加到mapView中

Swift 使用两个函数将注释添加到mapView中,swift,mapbox,Swift,Mapbox,我创建了这两个函数,当我调用函数pippo()时,我收到一个错误“致命错误:在展开可选值时意外发现nil”,为了修复此错误,我将此mapView.addAnnotation(hello)修改为mapView?.addAnnotation(hello),但我没有在地图中显示注释,如果我在caricamappa中调用pippo,注释被成功添加,但是我想分离函数加载映射并添加注释,这可能吗 func caricamappa(){ let styleURL = NSURL(string: "ma

我创建了这两个函数,当我调用函数pippo()时,我收到一个错误“致命错误:在展开可选值时意外发现nil”,为了修复此错误,我将此
mapView.addAnnotation(hello)
修改为
mapView?.addAnnotation(hello)
,但我没有在地图中显示注释,如果我在caricamappa中调用pippo,注释被成功添加,但是我想分离函数加载映射并添加注释,这可能吗

func caricamappa(){
    let styleURL = NSURL(string: "mapbox://**")
    let mapView = MGLMapView(frame: view.bounds,
                              styleURL: styleURL as URL?)
    mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]

    // Set the map’s center coordinate and zoom level.
    mapView.setCenter(CLLocationCoordinate2D(latitude: 46.370417,
                                              longitude: 8.411713),
                      zoomLevel: 13, animated: false)
    view.addSubview(mapView)
    mapView.delegate = self

}

func pippo(){
    let hello = MGLPointAnnotation()
    hello.coordinate = CLLocationCoordinate2D(latitude: 46.376362, longitude: 8.396907)
    hello.title = "Hello world!"
    hello.subtitle = "Welcome to my marker"

    // Add marker `hello` to the map.
    mapView.addAnnotation(hello)

}



override func viewDidLoad() {
    super.viewDidLoad()
    caricamappa()
    pippo()
}

您在
caricamappa
中定义了mapView,因此它在
pippo
中不存在。相反,将mapView设置为方法之外的IBOutlet。

好的,谢谢!!现在我看到了注释,但我需要使用函数func-mapView(u-mapView:MGLMapView,imageFor-annotation:MGLAnnotation)->MGLAnnotationImage?{如果让point=annotation作为?CustomPointAnnotation,而into-pippo无法使用此函数,对吗?很抱歉,我不理解您的问题。您能在原始帖子中添加更多代码吗?我会尽力提供帮助。