Swift 4 Codable; How to decode object with single root-level key

前端 未结 4 934
暖寄归人
暖寄归人 2020-12-02 13:21

I\'m using the Swift 4 Codable protocol with JSON data. My data is formatted such that there is a single key at the root level with an object value containing t

4条回答
  •  日久生厌
    2020-12-02 14:04

    Of course, you can always implement your own custom decoding/encoding — but for this simple scenario your wrapper type is a much better solution IMO ;)

    For comparison, the custom decoding would look like this:

    struct User {
        var id: Int
        var username: String
    
        enum CodingKeys: String, CodingKey {
            case user
        }
    
        enum UserKeys: String, CodingKey {
            case id, username
        }
    }
    
    extension User: Decodable {
        init(from decoder: Decoder) throws {
            let values = try decoder.container(keyedBy: CodingKeys.self)
    
            let user = try values.nestedContainer(keyedBy: UserKeys.self, forKey: .user)
            self.id = try user.decode(Int.self, forKey: .id)
            self.username = try user.decode(String.self, forKey: .username)
        }
    }
    

    and you still to conform to the Encodable protocol if you want to support encoding as well. As I said before, your simple UserWrapper is much easier ;)

提交回复
热议问题