我正试图用swift编写一个创建MKMapItem的函数,但遇到了String错误。这是代码:
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
}
}
替换此字符串:
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
}
您的副标题属性看起来像一个可选的String,但MKPlacemark
初始值设定项需要addressDictionary
的类型为[String : AnyObject]?
的参数。
这是什么意思?
所需的参数类型是一个字典,其中键为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
}
如果subtitle
为零,也可以返回可选的MKMapItem
对象。选择权在你;)