Type of 'title' has different optionality than required by protocol 'MKAnnotation'
Asked Answered
D

4

11

I followed the Ray Wenderlich MapKit tutorial in swift: http://www.raywenderlich.com/90971/introduction-mapkit-swift-tutorial and when I created Artwork class I got the error written in the title. I don't know what I have to do. This is the code:

class Artwork: NSObject, MKAnnotation {
let title: String
let locationName: String
let discipline: String
let coordinate: CLLocationCoordinate2D

init(title: String, locationName: String, discipline: String, coordinate: CLLocationCoordinate2D) {
    self.title = title
    self.locationName = locationName
    self.discipline = discipline
    self.coordinate = coordinate

    super.init()
}
}

Please help!

Dorsy answered 4/11, 2015 at 14:41 Comment(0)
B
20

The anser is in the documentation: we see on the MKAnnotation protocol reference page that the property title has to be an Optional.

Which is exactly what the error message is telling you: the optionality of title is incorrect.

Change it accordingly:

class Artwork: NSObject, MKAnnotation {

    var title: String?
    let locationName: String
    let discipline: String
    let coordinate: CLLocationCoordinate2D

    init(title: String, locationName: String, discipline: String, coordinate: CLLocationCoordinate2D) {
        self.title = title
        self.locationName = locationName
        self.discipline = discipline
        self.coordinate = coordinate

        super.init()
    }

}

ProTip: in Xcode, CMD+CLICK on your object or definition (MKAnnotation in your case) to see how the protocol is declared and what are its requirements.

Bashemeth answered 4/11, 2015 at 14:48 Comment(0)
G
3

The MKAnnotation protocol requires title to be an optional type:

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 }
}

Just declare you title variable as: let title: String? and the problem will go away.

Gaygaya answered 4/11, 2015 at 14:48 Comment(0)
I
1

Change it accordingly:

var title: String?

var subtitle: String?
Isreal answered 8/3, 2017 at 9:5 Comment(0)
G
0

With addition to the above as of 2016 swift 3

if you are following the above tutorial you will need to address the: var subtitle: String{ return locationName }

to : public var subtitle: String?{ return locationName }

Hope that too clarifies few things

Garnishee answered 2/2, 2017 at 16:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.