if let doesn't unwrap optional value for MKAnnotation's title property

蹲街弑〆低调 提交于 2019-12-11 17:24:19

问题


I want to unwrap optional value with if-let statement. I need to get title of MKAnnotation.

func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
    if let title = view.annotation?.title {
        print(title) //Optional("Moscow")
    }
}

Why if-let doesn't work here?


回答1:


The type of MKAnnotation.title is String??, it's a nested Optional, so you need to optional bind it twice.

func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
    if let optionalTitle = view.annotation?.title, let title = optionalTitle {
        print(title)
    }
}

Even though according to the documentation of MKAnnotation.title, the type of title should be String?, since title is declared as a non-required protocol property:

optional var title: String? { get }

when accessed through the MKAnnotation protocol type rather than the concrete type implementing the protocol, it becomes wrapped in another Optional, which represents the fact that the title property might not even be implemented by the concrete type implementing the protocol. Hence, when accessing the title property of an MKAnnotation object rather than an object with a concrete type conforming to MKAnnotation, the type of title will be String??.



来源:https://stackoverflow.com/questions/52605162/if-let-doesnt-unwrap-optional-value-for-mkannotations-title-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!