Guard let正在执行,但是之后的代码仍然有效?

问题描述

好,所以我有一个MapKit应用程序,刚刚完成了MKAnnotationView的设置。我的MKAnnotationView类看起来像这样:

class JumpSpotAnnotationView: MKMarkerAnnotationView {

override var annotation: MKAnnotation? {
    willSet {
        // Extra safe,making sure there's no errors
        guard (newValue as? JumpSpotAnnotation) != nil else {
            print("The JumpSpotAnnotation or JumpSpotAnnotationView has something wrong if you are reading this. (JumpSpotAnnotationView)")
            return
        }
        // Setting up UI for the little Callout bubble that appears when you tap the annotation to see more info
        canShowCallout = true
        calloutOffset = CGPoint(x: 0,y: 0)
        rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
        //detailCalloutAccessoryView
        markerTintColor = .blue
    }
}
}

我的视图控制器中的mapView viewFor函数如下所示:

extension ViewController: MKMapViewDelegate {

func mapView(_ mapView: MKMapView,viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    
    // Make sure the annotation entering the screen is a JumpSpotAnnotation,and exists
    guard let annotation = annotation as? JumpSpotAnnotation else {
        print("The JumpSpotAnnotation or JumpSpotAnnotationView has something wrong if you are reading this. (mapView viewFor func)")
        return nil
    }
    // Downcast the dequeued view as a JumpSpotAnnotationView,and make sure it has the same identifier as the registered JumpSpotAnnotationView above in viewDidLoad
    let dequeuedView = mapView.dequeueReusableAnnotationView(withIdentifier: "JumpSpotAnnotation") as? JumpSpotAnnotationView
    dequeuedView?.annotation = annotation
    // Return annotation views here
    return dequeuedView
}

}

老实说,我让每个人都守卫,因为我看到有人这样做,并认为这样做会更安全。除了确保注解实际上已进入视图中并且是否具有我指定的正确注解类型(我认为至少可以做到这一点)之外,我不确定自己的目的是什么。

无论如何,当我实际上通过在应用程序中按一个按钮添加注释时,一切都可以正常运行,完全符合我的期望,但是保护程序内部的打印语句将显示在调试器中。我不知道是什么原因造成的,也不知道为什么我的代码在触发后仍能正常工作,而后卫让我们执行的事实应该阻止它们下面的代码执行,并弄乱了我的应用程序。谁能提供想法或解释?我应该添加一下,一旦应用加载完毕,mapView viewFor func的打印语句就会出现一次,然后,每次添加注释时,JumpSpotAnnotationView的打印语句就会出现。

我想确保我不会错过一些巨大的错误,我会后悔。

解决方法

func mapView(_ mapView: MKMapView,viewFor annotation: MKAnnotation) -> MKAnnotationView?工作时,有些MKAnnotation不是JumpSpotAnnotation的类。它必须来自MKMapView,所以不必担心。您的guard let运行良好。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...