使用可编码协议创建CLLocationCoordinate2D

时间:2018-09-09 14:27:18

标签: swift mkannotation codable

我正在尝试使自定义类符合MKAnnotation协议。为了创建此类,我正在使用Codable协议从JSON feed进行解码。

class CustomClass: NSObject, Codable, MKAnnotation {

  var id: String
  var name: String
  var lat: Double?
  var lon: Double?
  var coordinate: CLLocationCoordinate2D

  // Note, the coordinate var is not a part of the decoded JSON file. 
  // It is derived from the lat and lon attributes, which are in the
  // JSON file.

  enum CodingKeys: String, CodingKey {
    case id
    case name
    case lat
    case lon
  }

  required init(from decoder: Decoder) throws {
    let values = try decoder.container(keyedBy: CodingKeys.self)
    self.id = try values.decode(String.self, forKey: .id)
    self.name = try values.decodeIfPresent(String.self, forKey: .name)
    self.lat = try values.decodeIfPresent(Double.self, forKey: .lat)
    self.lon = try values.decodeIfPresent(Double.self, forKey: .lon)
    self.coordinate = CLLocationCoordinate2D(latitude: self.lat!, longitude: self.lon!)
  }    
}

运行此代码时,在设置self.coordinate var的行中出现以下错误:

  

线程2:致命错误:展开一个可选值时意外发现nil

在对lat和lon变量进行解码之前,似乎已经设置了坐标变量。如何在init方法中使用解码的lat和lon var设置坐标var?

0 个答案:

没有答案