我有有效的工作代码,但我想知道是否有办法让它更简单、更小。
我有一个自定义类响应,可以从Json或文本初始化(取决于服务器的响应(
public class Response: Codable {
let responseP1: String?
let responseP2: String?
let responseP3: String?
enum CodingKeys: String, CodingKey {
case responseP1 = "someResponseCode1"
case responseP2 = "someResponseCode2"
case responseP3 = "someResponseCode3"
}
required init(_ response: [String: String]) {
self.responseP1 = response["someResponseCode1"]
self.responseP3 = response["someResponseCode2"]
self.responseP2 = response["someResponseCode3"]
}
required public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.responseP1 = try container.decode(String.self, forKey: .responseP2)
self.responseP3 = try container.decode(String.self, forKey: .responseP1)
self.responseP2 = try container.decode(String.self, forKey: .responseP3)
}
}
我能以某种方式将编码键和初始化与字典结合起来吗?
例如self.responseP1=响应[.responseP1]但是self.responseP1=response[CodingKeys.responseP1.rawValue]正在工作,但在这种情况下,我似乎一无所获
此外,我需要将其全部解析为字符串,但
public func encodeAsString() -> String? {
do {
let encodedResponse = try self.encoded()
return String(decoding: encodedResponse, as: UTF8.self)
} catch {
return nil
}
}
对我来说不起作用(即使是从Json而非Text初始化时也返回"{}"(,你能告诉我为什么吗?
如果您的目标只是能够编写self.responseP1 = response[.responseP1]
,那么您需要将Dictionary转换为正确的类型[CodingKeys: String]
。
private static func convertKeys(from response: [String: String]) -> [CodingKeys: String] {
Dictionary(uniqueKeysWithValues: response.compactMap {
guard let key = CodingKeys.init(stringValue: $0) else { return nil }
return (key: key, value: $1)
})
}
required init(_ response: [String: String]) {
let response = Self.convertKeys(from: response)
self.responseP1 = response[.responseP1]
self.responseP3 = response[.responseP2]
self.responseP2 = response[.responseP3]
}