代码之家  ›  专栏  ›  技术社区  ›  TheRedCamaro3.0 3.0

如何使Firestore的GeoPoint符合Swifts可编码协议?

  •  0
  • TheRedCamaro3.0 3.0  · 技术社区  · 7 年前

    GeoPoint 符合 Codable

    struct Landmark:Codable {
    let name:String
    let location:GeoPoint 
    }
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   Tristan Clet    5 年前

    你可以像这样把你的声明作为一个地质点:

    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 {}
    
        2
  •  -1
  •   Rico Crescenzio    7 年前

    extension GeoPoint: Codable {
    // custom codable implementation
    }