如何在Swift 4中制作可枚举的枚举? [英] How do I make an enum Decodable in swift 4?
本文介绍了如何在Swift 4中制作可枚举的枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
enum PostType: Decodable {
init(from decoder: Decoder) throws {
// What do i put here?
}
case Image
enum CodingKeys: String, CodingKey {
case image
}
}
我要怎么完成?
另外,可以说我将情况
更改为此:
What do i put to complete this?
Also, lets say i changed the case
to this:
case image(value: Int)
我如何使其符合可腐烂?
How do i make this conform to Decodable ?
EDit 这是我的完整代码(无效)
EDit Here is my full code (which does not work)
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
}
最终编辑
另外,它将如何处理这样的枚举?
Final Edit Also, how will it handle an enum like this?
enum PostType: Decodable {
case count(number: Int)
}
推荐答案
这很容易,只需使用 String
或 Int
隐式分配的原始值即可。
It's pretty easy, just use String
or Int
raw values which are implicitly assigned.
enum PostType: Int, Codable {
case image, blob
}
图像
编码为 0
和 blob
到 1
或
enum PostType: String, Codable {
case image, blob
}
图像
编码为图像
, 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)
}
这篇关于如何在Swift 4中制作可枚举的枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文