swift - '(AnyObject)' 不是 'NSObject' 的子类型

swift - '(AnyObject)' is not a subtype of 'NSObject'

我是 swift 开发的新手,我遵循了一个教程,一切都很好,直到我遇到这个错误,但我不知道如何修复它。 你能帮帮我吗?

if let json = response.result.value {
    let jsonArray:NSArray = json as! NSArray
    /// On fait la boucle pour avoir la liste globale des éléments a afficher
    for i in 0..<jsonArray.count {
        self.OPlays.append(Playlist(
            title:(jsonArray[i] as AnyObject).value(forKey: "title") as? String,
                artist:(jsonArray[i] as AnyObject).value(forKey: "artist") as? String,
                categorie:(jsonArray[i] as AnyObject).value(forKey: "categorie") as? String,
                cover_url:(jsonArray[i] as AnyObject).value(forKey: "cover_url") as? String)
        )
    }
    self.tableViewPlaylist.reloadData()
}        

新闻文件正确。

if let json = response.result.value {
    let jsonArray:NSArray = json as! NSArray

    /// On fait la boucle pour avoir la liste globale des éléments a afficher
    for i in 0..<jsonArray.count {
        self.OPlays.append(Playlist(
            id: (jsonArray[i] as AnyObject).value(forKey: "id") as? Int,
            title: (jsonArray[i] as AnyObject).value(forKey: "title") as? String,
            artist: (jsonArray[i] as AnyObject).value(forKey: "artist") as? String,
            cover_url: (jsonArray[i] as AnyObject).value(forKey: "cover_url") as? String,
            categorie: (jsonArray[i] as AnyObject).value(forKey: "categorie") as? String
        ))
    }
    self.tableViewPlaylist.reloadData()
}

我会删除所有 AnyObject 代码:

if let array = response.result.value as? [[String: Any]] {
    for dictionary in array {
        self.OPlays.append(Playlist(
            id: dictionary["id"] as? Int,
            title: dictionary["title"] as? String,
            artist: dictionary["artist"] as? String,
            categorie: dictionary["categorie"] as? String,
            cover_url: dictionary["cover_url"] as? String
        ))
    }
    self.tableViewPlaylist.reloadData
}

就个人而言,我会更进一步,不再手动解码您的 JSON。使用 JSONDecoder.

struct Playlist: Codable {
    let id: Int?
    let title: String?
    let artist: String?
    let categorie: String?
    let cover_url: String?
}

然后,假设您有 data 即展开的 Data 对象:

do {
    self.OPlays = JSONDecoder().decode([Playlist].self, from: data)
} catch {
    print(error)
}

或者,如果您使用的是 Alamofire,请考虑 Alamofire 5,它具有基于 JSONDecoderresponse 方法。