如何使Firestore的GeoPoint符合Swifts Codable协议?

时间:2018-12-09 23:13:21

标签: ios swift firebase google-cloud-firestore

我试图使来自Firestore查询的响应符合Swift 4可编码协议。但是我无法使GeoPoint符合Codable,因为该类已在Firestore库中声明。谢谢您的帮助。

struct Landmark:Codable {
let name:String
let location:GeoPoint 
}

2 个答案:

答案 0 :(得分:0)

您尝试使用扩展程序吗?

extension GeoPoint: Codable {
// custom codable implementation
}

基本上,该扩展允许您向现有的类/结构添加函数,计算的属性和协议一致性

答案 1 :(得分:0)

您可以像这样将声明保留为地理位置:

struct Landmark: Codable {
    let name: String
    let location: GeoPoint
}

但是您必须在文件中添加此扩展名,以使Swift知道Firebase地理位置的结构。

import FirebaseFirestore

fileprivate protocol CodableGeoPoint: Codable {
  var latitude: Double { get }
  var longitude: Double { get }

  init(latitude: Double, longitude: Double)
}

fileprivate enum GeoPointKeys: String, CodingKey {
  case latitude
  case longitude
}

extension CodableGeoPoint {
  public init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: GeoPointKeys.self)
    let latitude = try container.decode(Double.self, forKey: .latitude)
    let longitude = try container.decode(Double.self, forKey: .longitude)
    self.init(latitude: latitude, longitude: longitude)
  }

  public func encode(to encoder: Encoder) throws {
    var container = encoder.container(keyedBy: GeoPointKeys.self)
    try container.encode(latitude, forKey: .latitude)
    try container.encode(longitude, forKey: .longitude)
  }
}

extension GeoPoint: CodableGeoPoint {}