enum PostType: Decodable {

    init(from decoder: Decoder) throws {

        // What do i put here?
    }

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

我要用什么来完成这个?

case image(value: Int)

如何使其符合可解码的?

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

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

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)
}

Swift相关问答推荐

同步问题,发送Api Call之前未设置idToken

如何将泛型函数存储到变量中?

SwiftData:线程1:&Quot;NSFetchRequest找不到实体名称';提醒&q;的NSEntityDescription

仅使用@MainActor注释类的部分时的并发问题

如何使泡泡上的箭头直达封闭矩形

SwiftUI,如何更改具有多个按钮和一个布尔条件的一个按钮标签

循环字典中的数组

当将新值推送到 NavigationStack 时,SwiftUI 的 navigationDestination 已在堆栈的早期声明

BLE 在 ESP32 和 Iphone 之间发送字符串

如何在visionOS中将模型锚定在用户头部上方?

在 Swift 中将异步任务包装到 DispatchWorkItem 中以使其可取消?

If 语句在 Swift 中有 2 个日期

Firebase removeObserver 在 Swift 5 中不起作用

ScreenCaptureKit/CVPixelBuffer 格式产生意外结果

快速更改tableView中的数据

不使用 ViewController 时如何显示推送通知的alert 对话框

在 Swift 4 中,如何删除基于块的 KVO 观察者?

为什么我可以转换为 NSManagedObject 但不能转换为我的实体类型?

<<错误类型>> 奇怪的错误

swift - 我可以从我的自定义初始化方法中调用 struct 默认成员初始化吗?