[英]Swift: Print variable with different types (enum) from JSON in for-loop
The situation is like this: How to decode a JSON property with different types? 情况是这样的: 如何解码具有不同类型的JSON属性?
I used the code which is marked as solution in the linked question and I want to print a variable in a for loop: 我在链接的问题中使用了标记为解决方案的代码,并且希望在for循环中打印一个变量:
struct GetEvents: Decodable{
var id: String?
var expansion: String?
var distance: Distance?
}
enum Distance: Codable {
case int(Int)
case string(String)
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .int(let v): try container.encode(v)
case .string(let v): try container.encode(v)
}
}
init(from decoder: Decoder) throws {
let value = try decoder.singleValueContainer()
do {
self = .int(try value.decode(Int.self))
} catch DecodingError.typeMismatch {
self = .string(try value.decode(String.self))
}
}
enum ParseError: Error {
case notRecognizedType(Any)
}
}
I try to print all variables with a for-loop because i have multiple objects inside the object. 我尝试使用for循环打印所有变量,因为我在对象内部有多个对象。
for i in 0...(getEventsText.items.count - 1) {
if let idAsString = getEventsText.items[i].id {
print(idAsString)
}
if let distanceAsString = getEventsText.items[i].distance {
print(distanceAsString)
}
if let epansionAsString = getEventsText.items[i].offer_expansion {
print(expansionAsString)
}
I get the id and the expansion but the distance is showing as int(-1) and not as -1 我得到了id和扩展名,但距离显示为int(-1)而不是-1
If I just output it like this: 如果我只是这样输出:
for x in range getEventsText.items {
print(x)
}
It gives back 它回馈
GetEvents(id: Optional("7576"), distance: Swift.ImplicitlyUnwrappedOptional.some(DB_Read_enums_Test1.Distance.int(0)), expansion: Optional("0")) GetEvents(id:可选(“ 7576”),距离:Swift.ImplicitlyUnwrappedOptional.some(DB_Read_enums_Test1.Distance.int(0)),扩展:可选(“ 0”))
Let Distance
implement CustomStringConvertible
and add the following 让
Distance
实现CustomStringConvertible
并添加以下内容
var description: String {
switch self {
case let .int(value):
return "\(value)"
case let .string(value):
return value
}
}
enum Distance: Codable, CustomStringConvertible {
case int(Int)
case string(String)
var description: String {
switch self {
case let .int(value):
return "\(value)"
case let .string(value):
return value
}
//rest of code
}
Test case 测试用例
let data = """
{"id": "7576", "expansion": "0", "distance": -1}
""".data(using: .utf8)!
do {
let decoder = JSONDecoder()
let result = try decoder.decode(GetEvents.self, from: data)
print(String(describing: result.id))
print(String(describing: result.expansion))
print(String(describing: result.distance))
} catch {
print(error)
}
output is 输出是
Optional("7576")
Optional("0")
Optional(-1)
and if I change my json to "..."distance": "long"} then the last output row changes to 如果我将json更改为“ ...” distance“:” long“},则最后一个输出行将更改为
Optional(long)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.