gpt4 book ai didi

swift - 如何在 Swift 中制作枚举 Decodable?

转载 作者:IT王子 更新时间:2023-10-29 04:56:10 26 4
gpt4 key购买 nike

enum PostType: Decodable {

init(from decoder: Decoder) throws {

// What do i put here?
}

case Image
enum CodingKeys: String, CodingKey {
case image
}
}

我要做什么来完成这个?另外,假设我将 case 更改为:

case image(value: Int)

如何使它符合 Decodable?

这是我的完整代码(不起作用)

let jsonData = """
{
"count": 4
}
""".data(using: .utf8)!

do {
let decoder = JSONDecoder()
let response = try decoder.decode(PostType.self, from: jsonData)

print(response)
} catch {
print(error)
}
}
}

enum PostType: Int, Codable {
case count = 4
}

此外,它将如何处理这样的枚举?

enum PostType: Decodable {
case count(number: Int)
}

最佳答案

这很简单,只需使用隐式分配的 StringInt 原始值即可。

enum PostType: Int, Codable {
case image, blob
}

image 编码为 0blob 编码为 1

或者

enum PostType: String, Codable {
case image, blob
}

image 被编码为 "image"blob 被编码为 "blob"


这是一个如何使用它的简单示例:

enum PostType : Int, Codable {
case count = 4
}

struct Post : Codable {
var type : PostType
}

let jsonString = "{\"type\": 4}"

let jsonData = Data(jsonString.utf8)

do {
let decoded = try JSONDecoder().decode(Post.self, from: jsonData)
print("decoded:", decoded.type)
} catch {
print(error)
}

更新

在 iOS 13.3+ 和 macOS 15.1+ 中,允许编码/解码片段——未包装在集合类型中的单个 JSON 值

let jsonString = "4"

let jsonData = Data(jsonString.utf8)
do {
let decoded = try JSONDecoder().decode(PostType.self, from: jsonData)
print("decoded:", decoded) // -> decoded: count
} catch {
print(error)
}

在 Swift 5.5+ 中,甚至可以在没有任何额外代码的情况下对具有关联值的枚举进行编码/解码。这些值被映射到一个字典,并且必须为每个关联值指定一个参数标签

enum Rotation: Codable {
case zAxis(angle: Double, speed: Int)
}

let jsonString = #"{"zAxis":{"angle":90,"speed":5}}"#

let jsonData = Data(jsonString.utf8)
do {
let decoded = try JSONDecoder().decode(Rotation.self, from: jsonData)
print("decoded:", decoded)
} catch {
print(error)
}

关于swift - 如何在 Swift 中制作枚举 Decodable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44580719/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com