How do I make an enum Decodable in swift 4?

前端 未结 8 675
死守一世寂寞
死守一世寂寞 2020-11-28 20:16
enum PostType: Decodable {

    init(from decoder: Decoder) throws {

        // What do i put here?
    }

    case Image
    enum CodingKeys: String, CodingKey {
          


        
8条回答
  •  感情败类
    2020-11-28 21:00

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

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

    image is encoded to 0 and blob to 1

    Or

    enum PostType: String, Codable {
        case image, 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)
    }
    

提交回复
热议问题