[swift-users] Optional conformance warnings with Protocols

Rod Brown rodney.brown6 at icloud.com
Sat Jul 23 23:09:52 CDT 2016

Hi Swift Users,

I just ran across an issue where I had the following code:

class ManifestItem: NSObject {
    let value:    String
    let title:    String
    let subtitle: String?
    dynamic var coordinate: CLLocationCoordinate2D

As part of utilising this object, I needed it to conform to MKAnnotation, which declares:

public protocol MKAnnotation : NSObjectProtocol {
    // Center latitude and longitude of the annotation view.
    // The implementation of this property must be KVO compliant.
    public var coordinate: CLLocationCoordinate2D { get }
    // Title and subtitle for use by selection UI.
    optional public var title: String? { get }
    optional public var subtitle: String? { get }

I added the appropriate extension to “ManifestItem” and promptly got reminded with an error that MKAnnotation requires title be an optional.

To do this, I converted “title” in my ManifestItem class to be an implicitly unwrapped optional. This value can never be nil, and should be treated as such throughout my code. However, the compiler still emits a warning. "Type of 'title' has different optionality than expected by protocol ‘MKAnnotation' "

I’m wondering if this should be considered a bug? I am actually comforming correctly to the protocol - title is optional, though implicitly unwrapped. Should I have to make “title” optional, and every use of it optional or a force unwrap, when my code verifies that the manifest item is legitimately invalid if title property is nil?

I think this is valid use of the implicitly unwrapped optional. It allows you to say “this is optional for some reason, but should generally always be assumed to be non null.” This sounds remarkably similar to my use case "this is optional for conformance reasons, but should generally always be assumed to be non null.”

Thanks for your opinions,

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160724/9881159f/attachment.html>

More information about the swift-users mailing list