【问题标题】:GMSPath in swift Codable does not conform to protocol swiftswift Codable 中的 GMSPath 不符合 swift 协议
【发布时间】:2019-09-19 15:21:12
【问题描述】:

我创建了一个模型并使用了可编码的模型。我目前正在使用 GMSPath 获取路径,但是在添加到模型类时,我收到错误 Type 'EstimateResponse' does not conform to protocol 'Decodable'Type 'EstimateResponse' does not conform to protocol 'Encodable'

下面是我的模型

class EstimateResponse: Codable {

    var path: GMSPath? // Set by Google directions API call
    var destination: String?
    var distance: String?
}

感谢任何帮助

【问题讨论】:

  • 我猜你必须遵循手动方式而不是可编码

标签: ios swift google-maps gmsplace


【解决方案1】:

GMSPath 有一个encodedPath 属性(它是一个字符串),它也可以使用编码路径进行初始化。您只需要将您的 GMSPath 编码为其编码路径表示。

使用显式实现使 EstimateResponseCodable 一致:

class EstimateResponse : Codable {
    var path: GMSPath?
    var destination: String?
    var distance: String?

    enum CodingKeys: CodingKey {
        case path, destination, distance
    }
    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        let encodedPath = try container.decode(String.self, forKey: .path)
        path = GMSPath(fromEncodedPath: encodedPath)
        destination = try container.decode(String.self, forKey: .destination)
        distance = try container.decode(String.self, forKey: .distance)
    }

    func encode(to encoder: Encoder) throws {
        var container = try encoder.container(keyedBy: CodingKeys.self)
        try container.encode(path?.encodedPath(), forKey: .path)
        try container.encode(destination, forKey: .destination)
        try container.encode(distance, forKey: .distance)
    }
}

【讨论】:

  • 这给出了一些错误Argument type '() -> String' does not conform to expected type 'Encodable' A non-failable initializer cannot delegate to failable initializer 'init(fromEncodedPath:)' written with 'init?' Designated initializer cannot be declared in an extension of 'GMSPath'; did you mean this to be a convenience initializer?
  • 这是另一个错误Initializer requirement 'init(from:)' can only be satisfied by a 'required' initializer in the definition of non-final class 'GMSPath'
  • @King 照错误说的做。添加单词required
  • @Sweeper 在哪里?
  • 'required' initializer must be declared directly in class 'GMSPath' (not in an extension)
猜你喜欢
  • 1970-01-01
  • 2018-01-25
  • 1970-01-01
  • 1970-01-01
  • 2018-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-29
相关资源
最近更新 更多