如果let不解开MKAnnotation的title属性的可选值

时间:2018-10-02 08:59:49

标签: ios swift mkannotation

我想用if-let语句解开可选值。 我需要获得MKAnnotation的标题。

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

为什么if-let在这里不起作用?

1 个答案:

答案 0 :(得分:5)

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??.