Search code examples
mapkitswift2mkannotation

MKAnnotation - Cannot assign to property: 'title' is a get-only property


How do I resolve this build issue - I'm just trying to create an annotation for mapkit:

ERROR: "MKAnnotation - Cannot assign to property: 'title' is a get-only property"

import UIKit
import MapKit

class ViewController: UIViewController {

    @IBOutlet weak var mapView: MKMapView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Annotations
        var annotation:MKAnnotation
        annotation.title = "test"    // ** ISSUE IS HERE **         
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

Notes: - Have downloaded latest version of XCode - is this to do with Swift 2.0? -


Solution

  • MKAnnotation requires that the object inherit from NSObjectProtocol. To do that, you should have your class inherit from NSObject. You should declare your properties to match those of the MKAnnotation protocol.

    Example:

    class MapPin : NSObject, MKAnnotation {
        var coordinate: CLLocationCoordinate2D
        var title: String?
        var subtitle: String?
    
        init(coordinate: CLLocationCoordinate2D, title: String, subtitle: String) {
            self.coordinate = coordinate
            self.title = title
            self.subtitle = subtitle
        }
    }
    

    Usage:

    override func viewDidLoad() {
        super.viewDidLoad()
    
        // Annotations
        var annotation:MapPin
        annotation.title = "test"         
    }