微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决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运行良好。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。