Swift4 swift中的服务器通信错误处理
在服务器通信中,如果我们不知道将出现什么类型的数据,我们如何在Swift 4及更高版本中预先定义它是(字符串还是int) 也就是说,您如何假设数据是字符串还是整数,以及如何处理动态服务器数据的错误?{“响应”:{“id”:“353”,“规范”:[{“项目值”:3,“项目名称”:“里程”},{“项目值”:“二手车”,“项目名称”:“条件”},{“项目值”:“宝马”,“项目名称”:“制造”},{“项目值”:“7系列”,“项目名称”:“车型”},{“项目值”:2019,“商品名称”:“年份”},{“商品价值”:“两者”;“商品名称”:“首选销售渠道”},{“商品价值”:“asd”,“商品名称”:“出口地点”},,“说明”:“asd”,“lat_地点”:null,“isFavorite”:false,“用户id”:“156”,“标题”:“asd”,“卖家手机”:“971551909257”,“价格”:334,“地点”:“asd”,“日期”:“2019年11月4日”,“long_地点”:null,“图片”[],“结果”:1,“卖方id”:78} 查看上面json的模态类,在上面的json中,规范数组包含整数和字符串值,我们可以轻松地从中访问值。Swift4 swift中的服务器通信错误处理,swift4,swift5,Swift4,Swift5,在服务器通信中,如果我们不知道将出现什么类型的数据,我们如何在Swift 4及更高版本中预先定义它是(字符串还是int) 也就是说,您如何假设数据是字符串还是整数,以及如何处理动态服务器数据的错误?{“响应”:{“id”:“353”,“规范”:[{“项目值”:3,“项目名称”:“里程”},{“项目值”:“二手车”,“项目名称”:“条件”},{“项目值”:“宝马”,“项目名称”:“制造”},{“项目值”:“7系列”,“项目名称”:“车型”},{“项目值”:2019,“商品名称”:“年份”},{“商
struct GetResponse_DetailPage: Codable {
let response: Response_DetailPage?
}
struct Response_DetailPage: Codable {
let result: Int?
let id: String?
let sellerID: Int?
let sellerMobile: String?
let specification: [Specification_DetailPage]?
let images: [Image_DetailPage]?
let price: Int?
let location, responseDescription, date, latLocation: String?
let longLocation, title: String?
let isFavorite: Bool?
let userID: String?
enum CodingKeys: String, CodingKey {
case result, id
case sellerID = "seller_id"
case sellerMobile = "seller_mobile"
case specification, images, price, location
case responseDescription = "description"
case date
case latLocation = "lat_location"
case longLocation = "long_location"
case title, isFavorite
case userID = "user_id"
}
}
struct Image_DetailPage: Codable {
let adImg: String?
enum CodingKeys: String, CodingKey {
case adImg = "ad_img"
}
}
struct Specification_DetailPage: Codable {
let itemName : String?
let itemValue: ItemValue_DetailPage?
enum CodingKeys: String, CodingKey {
case itemName = "item_name"
case itemValue = "item_value"
}
}
enum ItemValue_DetailPage: Codable {
case intege(String)
case string(String)
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let x = try? container.decode(Int.self) {
self = .intege(String(describing: x))
return
}
if let x = try? container.decode(String.self) {
self = .string(x)
return
}
throw DecodingError.typeMismatch(ItemValue_DetailPage.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for ItemValue"))
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .intege(let x):
try container.encode(x)
case .string(let x):
try container.encode(x)
}
}
}
查看此内容,如果您有问题,请发表评论请使用json示例澄清问题,如果可能,请说明您迄今为止的尝试。