How do I make an enum Decodable in swift 4?

前端 未结 8 684
死守一世寂寞
死守一世寂寞 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:17

    Swift would throw a .dataCorrupted error if it encounters unknown enum value. If your data is coming from a server, it can send you an unknown enum value at any time (bug server side, new type added in an API version and you want the previous versions of your app to handle the case gracefully, etc), you'd better be prepared, and code "defensive style" to safely decode your enums.

    Here is an example on how to do it, with or without associated value

        enum MediaType: Decodable {
           case audio
           case multipleChoice
           case other
           // case other(String) -> we could also parametrise the enum like that
    
           init(from decoder: Decoder) throws {
              let label = try decoder.singleValueContainer().decode(String.self)
              switch label {
                 case "AUDIO": self = .audio
                 case "MULTIPLE_CHOICES": self = .multipleChoice
                 default: self = .other
                 // default: self = .other(label)
              }
           }
        }
    

    And how to use it in a enclosing struct:

        struct Question {
           [...]
           let type: MediaType
    
           enum CodingKeys: String, CodingKey {
              [...]
              case type = "type"
           }
    
    
       extension Question: Decodable {
          init(from decoder: Decoder) throws {
             let container = try decoder.container(keyedBy: CodingKeys.self)
             [...]
             type = try container.decode(MediaType.self, forKey: .type)
          }
       }
    

提交回复
热议问题