If Let Doesn't Unwrap Optional Value for Mkannotation's Title Property

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

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

Can you safely unwrap nested optionals in swift in one line?

You could do it like so:

if let title = view.annotation?.title as? String {

}

view.annotation?.title is a double optional string: String?? since both the property annotation of an MKAnnotationView, and its own property title, are optional.


You could also use the guard statement like so:

guard let title = view.annotation?.title as? String else {
return
}
//use title in the rest of the scope

you could also use a switch statement :

switch title {
case .some(.some(let t)):
//use the title here
print(t)
default:
break
}


Related Topics



Leave a reply



Submit