Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 303
Adela Toderici Avatar asked Nov 04 '15 14:11

Adela Toderici


3 Answers

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.

like image 131
Eric Aya Avatar answered Nov 15 '22 13:11

Eric Aya


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.

like image 43
Danny Bravo Avatar answered Nov 15 '22 12:11

Danny Bravo


Change it accordingly:

var title: String?

var subtitle: String?
like image 45
alpertolgagunduzay Avatar answered Nov 15 '22 12:11

alpertolgagunduzay