【问题标题】:How to make GMSPlace Codable?如何使 GMSPlace 可编码?
【发布时间】:2021-08-05 08:23:28
【问题描述】:

有人想让 GSMPlace 成为可从 googleplaces 编码的吗?

我想要的是,将 GMSPlace 数据(地点和名称)存储到 UserDefaults 中,然后从 UserDefaults 中检索并存储回destinationPlace。

import Foundation
import RxSwift
import RxCocoa
import GooglePlaces

class SearchViewModel {

    var destinationPlace: BehaviorRelay<GMSPlace?> = BehaviorRelay(value: nil)

    var isValid: Bool {
        if destinationPlace.value != nil {
            return true
        }
        return false
    }
}

【问题讨论】:

    标签: ios swift codable


    【解决方案1】:

    我不知道GooglePlaces 或对象类型GMSPlace 的任何细节。

    但是在 Swift 中,如果你想给一个类添加一些东西,你可以创建一个扩展,可选地向它添加协议并添加函数。在您的情况下,它看起来像这样:

    extension GMSPlace: Codable {
    
        enum CodingKeys: String, CodingKey {
            case propertyName1
            case propertyName2
            ...
        }
        
        public init(from decoder: Decoder) throws {
            let container = try decoder.container(keyedBy: CodingKeys.self)
            propertyName1 = try container.decode(String.self, forKey: .propertyName1)
            propertyName2 = try container.decode(Int.self, forKey: .propertyName2)
        }
        
        public func encode(to encoder: Encoder) throws {
            var container = encoder.container(keyedBy: CodingKeys.self)
            try container.encode(propertyName1, forKey: .propertyName1)
            try container.encode(propertyName2, forKey: .propertyName2)
        }
    }
    

    您必须弄清楚需要包含哪些属性、需要映射到哪些类型等细节。

    如果这对您造成问题,您还应该在某处为他们打开一张票,以便将其添加到 SDK 中

    【讨论】:

    • 我遇到了这两个错误 1. 初始化器要求 'init(from:)' 只能由非最终类 'GMSPlace' 的定义中的 'required' 初始化器来满足 2.'let'属性“名称”可能无法直接初始化;改用“self.init(...)”或“self = ...”
    • 当我在 init 方法中写 required 时,它说 write required in GMSPlace Class ,你能告诉我在 GMSPlace 中我应该在哪里写 required
    • @Dhiren required 需要在 public 和 init 之间添加,所以 public required init(from ...)。第二个错误是告诉您属性name 需要在初始化结束时设置一个值,而您没有设置一个。它告诉您要么自己设置一个,要么在超类上调用一个 init 以完成其余的 init。值得您花时间研究一下 Codable 是什么,它是如何工作的,以及为什么在尝试挤入它之前需要它。可编码是 Swift 的一个非常重要的方面:raywenderlich.com/3418439-encoding-and-decoding-in-swift
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-05
    • 2020-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多