Swift 4 Codable Array's

前端 未结 4 1210
半阙折子戏
半阙折子戏 2021-02-02 14:04

So I have an API route that returns a JSON array of objects. For example:

[
    {\"firstname\": \"Tom\", \"lastname\": \"Smith\", \"age\": 31},
    {\"firstname\         


        
4条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-02 14:57

    Swift 5 Using Codable

    Alamofire Generic Response

    PersonModel.swift (create with SwiftyJsonAccelerator)

    import Foundation
    
    class PersonModel: Codable {
    
      enum CodingKeys: String, CodingKey {
        case age
        case firstname
        case lastname   }
    
      var age: Int?   var firstname: String?   var lastname: String?
    
      init (age: Int?, firstname: String?, lastname: String?) {
        self.age = age
        self.firstname = firstname
        self.lastname = lastname   }
    
      required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        age = try container.decodeIfPresent(Int.self, forKey: .age)
        firstname = try container.decodeIfPresent(String.self, forKey: .firstname)
        lastname = try container.decodeIfPresent(String.self, forKey: .lastname)   }
    
    }
    

    Generic Get Response

    func genericGET(urlString: String, completion: @escaping (T?) -> ()) {
    
    Alamofire.request(urlString)
        .responseJSON { response in
            // check for errors
            switch response.result {
            case .success(_):
    
                do {
                    let obj = try JSONDecoder().decode(T.self, from: response.data!)
                    completion(obj)
                } catch let jsonErr {
                    print("Failed to decode json:", jsonErr)
                }
    
                break
            case .failure(_):
    
    
                completion(nil)
    
                break
            }
    }
    
    }
    

    Call this method

    genericGET(urlString: "YOUR_URL") { (persons: [PersonModel]?) in
        print(persons?[0].firstname)
    }
    

提交回复
热议问题