【问题标题】:Custom MKAnnotation dictionary input (CLLocationCoordinate2d)自定义 MKAnnotation 字典输入 (CLLocationCoordinate2d)
【发布时间】:2016-05-03 13:08:37
【问题描述】:
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
        }

    }

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

有什么办法解决这个问题吗?

感谢您的建议。

【问题讨论】:

  • 自定义构造函数的第一行应该是“super.init()”[这正是错误消息告诉你的内容]
  • 我正在添加这一行,但它写入相同的错误:属性 self.coordinate 未在 super.init 调用时初始化
  • 因为coordinate不是Optional,所以必须为控制流的每个分支初始化。
  • var coordinate = CLLocationCoordinate2D(),但你确定你在做什么吗? MKAnnotation 已经有一个属性“坐标”..
  • 我正在使用 Firebase,Firebase 的输出是字典,我需要字典中的所有键并设置值。

标签: swift dictionary mapkit mkannotation


【解决方案1】:

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

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
      }
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-19
    • 2015-08-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多