如何在 swift 4 中使枚举可解码? [英] How do I make an enum Decodable in swift 4?

查看:19
本文介绍了如何在 swift 4 中使枚举可解码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

enum PostType: Decodable {

    init(from decoder: Decoder) throws {

        // What do i put here?
    }

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

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

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

推荐答案

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

It's pretty easy, just use String or Int raw values which are implicitly assigned.

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

image 编码为 0blob 编码为 1

image is encoded to 0 and blob to 1

或者

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

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

image is encoded to "image" and blob to "blob"

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

This is a simple example how to use it:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆