问题
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