Swift: 如何在地图视图上启用和禁用注释?

Swift: How to enable and disable annotations on map view?

我有一段代码可以在地图视图上显示一些注释。但是,我正在尝试使用一些功能,当用户点击 UISwitch 按钮时可以启用或禁用它。关于如何实现这一目标的任何建议?提前致谢!

 let theHouse = MKPointAnnotation()
        theHouse.coordinate = CLLocationCoordinate2D(latitude: 38.8977, longitude: -77.0365)

    theHouse.title = "The House, DC"
        theHouse.subtitle = "New Jersey, DC"

    myMapView.addAnnotation(theHouse)
    myAnnotations.append(theHouse.title!)

    //Switch that toggles the annotation...
    @IBAction func turnOffAnnotations(_ sender: UISwitch) {
    //Code that enables and disables the annotation?

if toggle.isOn{
    let visible = myMapView.visibleMapRect
    let inRect = myMapView.annotations(in: visible)

    for annotation: MKAnnotation in myMapView.annotations{
        if (inRect.contains(anno as! AnyHashable)){
          myMapView.removeAnnotation(annotation)
        }
    }
    } else {
        let visible = myMapView.visibleMapRect
        let inRect = myMapView.annotations(in: visible)

        for annotation: MKAnnotation in myMapView.annotations{
            if (inRect.contains(anno as! AnyHashable)){
                myMapView.addAnnotation(annotation)
            }
        }
    }
//How to add back the removed annotations here?...
    }

使用viewFor(annotation : MKAnnotation)方法:

Swift 3

@IBAction func changeAnnotationsVisibility(_ sender: UISwitch) {
    let annotationVisible = sender.isOn

    for annotation in myMapView.annotations {
        myMapView.view(for: annotation)?.isHidden = !annotationVisible
    }
}