Swift - Create data model from JSON response

后端 未结 6 2093
小鲜肉
小鲜肉 2021-02-02 01:08

I\'m learning Swift lang and one of the things that would be great to hear others input about is \"How you handle models from JSON responses\"? For example -

I have

6条回答
  •  我在风中等你
    2021-02-02 01:45

    I would suggest using SwiftyJSONModel there your model would look something like:

    import SwiftyJSONModel
    
    class User: NSObject, JSONObjectInitializable {
        enum PropertyKey : String {
            case user_token, email
        }
    
        var user_token:String?
        var email:String?
    
        required init(object: JSONObject) throws {
            user_token = object.value(for: .user_token)
            email = object.value(for: .email)
        }
    }
    

    This library has 3 nice things:

    1. You don't have to explicitly cast to String as library will infer the type
    2. You can have non-optional properties and library will tell you which exact field was wrong
    3. All the keys to the model are incapsulated in enum which gives you auto-complition when you type the keys and guarantees that you cannot access keys, that are not in enum

提交回复
热议问题