[英]Decoding an Enum in Swift with Associated Values
我正在嘗試解碼由關聯值組成的枚舉。 我正在嘗試以下方法,但它不斷拋出異常。
let jsonString = """
{
"route": "petDetails"
}
"""
let jsonData = jsonString.data(using: .utf8)
struct Post: Decodable {
let route: Route
}
enum Route: Decodable, Equatable {
case petDetails(String)
init?(rawValue: String) {
switch rawValue {
case "petDetails":
self = .petDetails("")
default:
return nil
}
}
private enum CodingKeys: String, CodingKey {
case petDetails
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
if let value = try? container.decode(String.self, forKey: .petDetails) {
self = .petDetails(value)
} else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: container.codingPath, debugDescription: "Data doesn't match"))
}
}
}
try! JSONDecoder().decode(Post.self, from: jsonData!)
我收到以下錯誤:
Fatal error: 'try!' expression unexpectedly raised an error: Swift.DecodingError.typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "route", intValue: nil)], debugDescription: "Expected to decode Dictionary<String, Any> but found a string/data instead.", underlyingError: nil))
有什么我想念的想法嗎?
假設我們有一個帶有關聯值的枚舉:
enum Route: Codable, Equatable {
case petDetails(name: String)
case petListing(count: Int)
...
代表每個Route
的 JSON 應該包含兩個值:
petDetails
與petListing
),以及我們的編碼鍵將是
private enum CodingKeys: String, CodingKey {
case type
case associatedValue
}
和解碼功能將是
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let type = try container.decode(String.self, forKey: .type)
switch type {
case "petDetails":
// The associated value is a String
let name = try container.decode(String.self, forKey: .associatedValue)
self = .petDetails(name: name)
case "petListing":
// The associated value is an Int
let count = try container.decode(Int.self, forKey: .associatedValue)
self = .petListing(count: count)
default:
throw DecodingError.dataCorruptedError(forKey: .type, in: container, debugDescription: "Invalid type")
}
}
我們首先對類型進行解碼,這會告訴我們關聯的值將是什么類型的數據。
Post
的 JSON 看起來像
{
"route": {
"type": "petDetails",
"associatedValue": "Rex"
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.