我有一個類似這樣的 json 回應:
"Details": {
"Attachments": [],
"place": {
"destination": {
"type": "international",
"Id": "superman",
"locationType": "City",
"Name": "Kent"
},
"package": 52.32,
"description": "Dinner"
}
}
}
在這個回應中,destination 中的所有引數都是可選的,除了型別,所以我像這樣處理這個回應:
public struct Destination: Decodable, Equatable {
public let Id: String?
public let Name: String?
public let city: String?
public let locationType: String?
public let pinCode: String?
public let country: String?
public let state: String?
public let currency: String?
public let language: String?
public let type: Type
}
由于所有引數都是可選的,并且基于型別,因此我將僅獲得其中幾個引數作為回應。喜歡 -
type: "international",
country: "US"
id: "5",
currency: "Dollar"
有什么辦法可以在列舉中寫這個:
enum Destination {
case international(country: String, id: String, currency: String)
case national(state: String, language: String, pincode: String)
}
誰能回答我應該如何從這種方法開始。謝謝
uj5u.com熱心網友回復:
由于具有關聯值的 Swift 5.5 列舉具有Codable 綜合,但這需要頂級容器包含與列舉案例名稱匹配的單個鍵。在您的情況下,您確定容器內的值是多少,因此唯一的解決方案是init(from decoder: Decoder)自己撰寫,解碼所有關聯的值,然后回傳列舉值。
像這樣的東西會起作用:
public struct Place: Decodable {
var destination: Destination
}
enum Destination: Decodable {
case international(country: String?, Id: String?, currency: String?)
case national(state: String?, language: String?, pincode: String?)
enum CodingKeys: String, CodingKey {
case type
case country
case Id
case currency
}
init(from decoder: Decoder) throws {
var container = try decoder.container(keyedBy: CodingKeys.self)
let type = try container.decode(String.self, forKey: .type)
let country = try container.decodeIfPresent(String.self, forKey: .country)
let Id = try container.decodeIfPresent(String.self, forKey: .Id)
let currency = try container.decodeIfPresent(String.self, forKey: .currency)
switch type {
case "international":
self = Destination.international(country: country, Id: Id, currency: currency)
case "national":
fatalError("not supported yet")
() // similary
default:
fatalError("not supported yet")
() // throw an decoding error
}
}
}
以上內容適用于您提供的 JSON:
let json = """ {
"destination": {
"type": "international",
"Id": "superman",
"country": "City",
"currency": "Kent"
} } """
do {
let data = try JSONDecoder().decode(Place.self, from: json.data(using: .utf8)!)
}
catch {
print("error \(error)")
}
uj5u.com熱心網友回復:
struct Details: Decodable {
enum CodingKeys: String, CodingKey {
case Attachments, place
}
let Attachments: Array?
let place: Place?
}
struct Place: Decodable {
let destination: Destination?
let package: Double?
let description: String?
}
struct Destination: Decodable {
let type, Id, locationType, Name: String?
}
uj5u.com熱心網友回復:
您必須撰寫列舉,例如
Enum CodingKeys: String, CodingKey {
case Id, Name, city, locationType, pinCode, country, state, currency, language = String?
case type = Type
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/512851.html
標籤:IOS迅速枚举
上一篇:SwiftiOS布局約束。以編程方式使用與視圖高度成比例的常量
下一篇:左右滑動后轉換集合視圖單元格容器
