MKAnnotationView has double optionals

If I implement MKMapViewDelegate like so:


    func mapView(mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
        guard let item = view.annotation else { return }


and then I try to look at item.title, it's showing as a String?? instead of a String? in Xcode 7.1.1


If I control-click on annotation it says it's an MKAnnotation? like I'd expect. Control-clicking on that shows title defined like so, which looks correct to me. Is this a bug I need to report?


optional public var title: String? { get }

Accepted Reply

You end up with two levels of optionality because:

  • within the MKAnnotation protocol, the

    title
    property is optional
  • if that property is implemented, the value it returns is optional

I’m not sure if there’s a nicer way to access

title
but the following seems to work:
if let os = item.title, let s = os {
    print(s)
}

Share and Enjoy

Quinn "The Eskimo!"
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

Replies

You end up with two levels of optionality because:

  • within the MKAnnotation protocol, the

    title
    property is optional
  • if that property is implemented, the value it returns is optional

I’m not sure if there’s a nicer way to access

title
but the following seems to work:
if let os = item.title, let s = os {
    print(s)
}

Share and Enjoy

Quinn "The Eskimo!"
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

I ended up doing the double let as well, thanks. So the first one is basically an "if they implemented the optional getter" and then the second one is "does it have a value".


Makes sense, even though it's super ugly 🙂

If you just want to collapse the double optional you can use “?? nil” which gets you to a single level of optionality.