作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
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)
}
最佳答案
这很简单,只需使用隐式分配的 String
或 Int
原始值即可。
enum PostType: Int, Codable {
case image, blob
}
image
编码为 0
,blob
编码为 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/52950312/
我是一名优秀的程序员,十分优秀!