无法将 JSON 中的值附加到 Swift 中的数组

Having trouble appending value from JSON Parsing to array in Swift

我正在尝试 https://jsonplaceholder.typicode.com and I'm trying to create a list of the albums. I tried following ,但专辑标题列表未显示在 TableView 上。我错过了什么?

class AlbumTableVC: UITableViewController {

var albums = [Album]()

override func viewDidLoad() {
    super.viewDidLoad()
    fetchAlbums()
}

func fetchAlbums() {
    AF.request("https://jsonplaceholder.typicode.com/albums").responseJSON { (response) in
        switch response.result {
        case .success(let value):
            let json = JSON(value)
            
            for value in json.arrayValue {
                let id = value.dictionaryValue["id"]!.int
                let userId = value.dictionaryValue["userId"]!.int
                let title = value.dictionaryValue["title"]!.string
                
                let album = Album(id: id, userId: userId, title: title)
                self.albums.append(album)
            }
        case .failure(let error):
            print(error)
        }
    }
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return albums.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "AlbumCell", for: indexPath)
    
    let album = albums[indexPath.row]
    cell.textLabel?.text = album.title
    
    return cell
}}

填充数据源(异步)后,您必须重新加载 table 视图

for value in json.arrayValue {
    let id = value.dictionaryValue["id"]!.int
    let userId = value.dictionaryValue["userId"]!.int
    let title = value.dictionaryValue["title"]!.string
    
    let album = Album(id: id, userId: userId, title: title)
    self.albums.append(album)
}
self.tableView.reloadData()

考虑放弃 SwiftyJSON 以支持 Codable。连Alamofire都支持。

看看这个简化的代码,你只需要Album采用Decodable

struct Album : Decodable { ...

AF.request("https://jsonplaceholder.typicode.com/albums").responseDecodable { (response : DataResponse<[Album],AFError>) in
    switch response.result {
    case .success(let value):
        self.albums = value
        self.tableView.reloadData()
        
    case .failure(let error):
        print(error)
    }
}