swift - 自定义 MKAnnotation 字典输入 (CLLocationCooperative2d)

标签 swift dictionary mapkit mkannotation

import MapKit
import UIKit

class Point: NSObject, MKAnnotation {
    var id: String?
    var title: String?
    var coordinate: CLLocationCoordinate2D
    var subtitle: String?



    init(id: String, dictionary: Dictionary<String, AnyObject>){


        self.id = id

        if let title = dictionary["title"] as? String {
            self.title = title
        }

        if let subtitle = dictionary["subtitle"] as? String {
            self.subtitle = subtitle
        }

        if let coords = dictionary["coordinates"] as? [String:[String:Double]] {
            var latitude = coords.values.first!["latitude"]!
            var longitude = coords.values.first!["longitude"]!
            var location = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
            self.coordinate = location
        }

    }

错误:在隐式生成的 super.init 调用中未初始化属性 self.coordinate。

知道如何解决这个问题吗?

感谢您的一些建议。

最佳答案

您应该在其他情况下分配默认值

if let coords = dictionary["coordinates"] as? [String:[String:Double]] {
...
} else {
self.coordinate = <assign a default location>
}

或者

如果没有坐标,则不应创建对象。所以让你的 init 成为可选的。

 init?(id: String, dictionary: Dictionary<String, AnyObject>){

      if let coords = dictionary["coordinates"] as? [String:[String:Double]] {
           self.id = id

           if let title = dictionary["title"] as? String {
                self.title = title
           }

           if let subtitle = dictionary["subtitle"] as? String {
                self.subtitle = subtitle
           }
           var latitude = coords.values.first!["latitude"]!
           var longitude = coords.values.first!["longitude"]!
           var location = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
           self.coordinate = location
      } else {
           return nil
      }
 }

关于swift - 自定义 MKAnnotation 字典输入 (CLLocationCooperative2d),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37005077/

相关文章:

ios - 如何快速从我的 map View 上的特定点获取经度和纬度?

mapkit - 如何判断 CLLocationManager 是否正在监视重大位置更改

ios - 为什么它不能在 swift 2 的 Playground 上显示任何东西?

ios - UITableView 在快速滚动期间卡住

ios - 用户移动 map 时快速打印 map 中心

Python 查询最旧日期列表

python - 在 For 循环中创建字典时防止覆盖嵌套字典值

ios - 如何在 Swift 中禁用键盘上的 "Space"键?

arrays - 追加到字典中的数组值

ios - Swift MKMapView 有时会变为 nil 并且应用程序崩溃