如何将来自网络的数据存储在数组中 api

How to store data in array from web api

我正在使用 Xcode 11.3.1,Swift 5 并尝试通过 Web api 在 table 视图中显示数据。因此,在获取数据后,我想将 "name" 数据存储在 countryList 中。 countryList 是一个数组。

URLSession.shared.dataTask(with: url!) { (data, response, error) in

        do
        {if error == nil{

            let parsedData = try JSONSerialization.jsonObject(with: data!) as? NSDictionary
            let tableData = parsedData?["data"] as! NSArray

            self.countryList = [tableData.value(forKey: "name") as? String]
            print("DEVELOPER: \(self.countryList)")

            DispatchQueue.main.async {
                self.countryTable.reloadData()
            }
            }
        }
        catch{
            print(error.localizedDescription)
        }

    }.resume()

//网络Api

{ "status": 200, "data": [ { "name": "Afghanistan", "id": 1 }, { "name": "Albania", "id": 2 }, { "name": "Algeria", "id": 3 }, { "name": "American Samoa", "id": 4 } ], "message": "List of all countries." }

尝试

guard let data = data else { return }
let parsedData = try JSONSerialization.jsonObject(with: data) as! [String:Any]
let tableData = parsedData["data"] as! [[String:Any]] 
self.countryList = tableData.compactMap {  [=10=]["name"] as? String }

重新开始

do { 
   let res = try JSONDecoer().decode(Root.self,from:data)
    print(res.data)
 }
catch {
   print(error)
 }

struct Root : Codable {
   let status:Int
   let data:[Model]
}

struct Model:Codable {
  let name:String
  let id:Int
}