我试图用MKMapItem编写一个函数,但是我得到了一个字符串错误。以下是代码:
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
}当我试图创建placemark时,我得到了以下错误:
无法转换"String : String?“类型的值?参数类型"String : AnyObject?
完整的类代码:
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
}
}发布于 2016-07-04 11:31:32
替换此字符串:
let title: String?替换此代码:
var subtitle: String? {
return locationName
}您需要将字幕转换为AnyObject,如下所示:
let addressDict = [String(kABPersonAddressStreetKey): self.subtitle as! AnyObject]"func mapItem() -> MKMapItem { }“的完整代码是:
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
}发布于 2016-04-18 14:38:33
您的subtitle属性看起来像一个可选字符串,但是MKPlacemark初始化程序需要一个类型为[String : AnyObject]?的addressDictionary参数。
那是什么意思?
预期的参数类型是一个字典,其中键是String,值是AnyObject类型,所以它可以是任何东西。任何东西除了零值!但是您的subtitle属性可以是零,因此您有此错误。
在使用之前,打开您的值:
func mapItem() -> MKMapItem {
var addressDictionary : [String:String]?
if let subtitle = subtitle {
// The subtitle value used here is a String,
// so addressDictionary conforms to its [String:String] type
addressDictionary = [String(kABPersonAddressStreetKey): subtitle
}
let placemark = MKPlacemark(coordinate: coordinate, addressDictionary: addressDictionary)
let mapItem = MKMapItem(placemark: placemark)
mapItem.name = title
return mapItem
}如果MKMapItem为零,也可以返回一个可选的subtitle对象。这是你的选择;)
https://stackoverflow.com/questions/36696702
复制相似问题