我有一個 API 回應,它回傳一個型別不一致的 JSON 欄位。因此,我去https://www.quicktype.io尋求幫助并找到了一個模型。
這是我遇到問題的模型部分:
struct MyModel: Codable {
let id: ID?
}
enum ID: Codable {
case integer(Int)
case string(String)
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let x = try? container.decode(Int.self) {
self = .integer(x)
return
}
if let x = try? container.decode(String.self) {
self = .string(x)
return
}
throw DecodingError.typeMismatch(ID.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for ID"))
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .integer(let x):
try container.encode(x)
case .string(let x):
try container.encode(x)
}
}
}
我有一個完全解碼的回應,當我嘗試列印該值時,我得到如下資訊:
Optional(MyApp.ID.integer(27681250))
或者
Optional(MyApp.ID.string(27681250))
我這樣做:
print(modelData?.id)
我想訪問我得到的確切值,但我無法這樣做。我嘗試將其轉換為其他型別,但沒有幫助。任何幫助表示贊賞。謝謝。
uj5u.com熱心網友回復:
有許多不同的方法可以做到這一點。所有這些都在The Swift Programming Language一書中的Enumerations部分進行了解釋。
這只是其中一種方法......
func example(id: ID) {
switch id {
case let .integer(value):
<#code#>
case let .string(value):
<#code#>
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/381565.html
下一篇:從結構資料SwiftUI創建陣列
