Search code examples
iosswiftmkplacemark

Argument type error on MKPlacemark


I'm trying to write in swift a function that create a MKMapItem but I get a String error. Here is the code:

func mapItem() -> MKMapItem {
    let addressDictionary = [String(kABPersonAddressStreetKey): subtitle]
    let placemark = MKPlacemark(coordinate: coordinate, addressDictionary: addressDictionary)

    let mapItem = MKMapItem(placemark: placemark)
    mapItem.name = title

    return mapItem
}

I got the following error when I try to create placemark:

Cannot convert value of type "[String : String?]" to expected argument type "[String : AnyObject]?

Full class code :

class Bar: NSObject, MKAnnotation {

    // MARK: Properties
    let id: Int
    let title: String
    let locationName: String
    let url: String
    let imageUrl: String
    let tags: String
    let coordinate: CLLocationCoordinate2D

    // MARK: Initialisation
    init(id: Int, adress: String, name: String, url: String, tags: String, imageUrl: String, coordinate: CLLocationCoordinate2D) {
        // Affectation des attributs
        self.id = id
        self.title = name
        self.locationName = adress
        self.url = url
        self.imageUrl = imageUrl
        self.tags = tags
        self.coordinate = coordinate
    }

    // MARK: Subtitle

    var subtitle: String {
        return locationName
    }

    // MARK: Helper

    func mapItem() -> MKMapItem {
        var addressDictionary : [String:String]?
        addressDictionary = [String(kABPersonAddressStreetKey): subtitle]

        let placemark = MKPlacemark(coordinate: coordinate, addressDictionary: addressDictionary)

        let mapItem = MKMapItem(placemark: placemark)
        mapItem.name = title

        return mapItem
    }    
}

Solution

  • Replace this string :

      let title: String?
    

    Replace this code :

     var subtitle: String? {
            return locationName
        }
    

    You need to cast your subtitle as AnyObject as shown below:

    let addressDict = [String(kABPersonAddressStreetKey): self.subtitle as! AnyObject]
    

    and your complete code for "func mapItem() -> MKMapItem { }" will be:

    func mapItem() -> MKMapItem {
        let addressDict = [String(kABPersonAddressStreetKey): self.subtitle as! AnyObject]
        let placemark = MKPlacemark(coordinate: self.coordinate, addressDictionary: addressDict)
    
        let mapItem = MKMapItem(placemark: placemark)
        mapItem.name = self.title
    
        return mapItem
      }