-2
我遇到以下代碼的問題。我正在下載JSON中的演員列表,我想用接收的數據填充Struct Actor。一切工作都很好,直到我試圖flatMap接收到的數據並嘗試初始化struct Actor。當我嘗試編譯代碼時,出現錯誤:無法將類型'()'的值分配給類型[Actor]。該錯誤對應於viewDidLoad actorsList = downloadActors()中的一行有人會推薦誰來解決這個問題嗎?帶有JSON和flatMap的Struct Init
import UIKit
func downloadActors() {
var request = URLRequest(url: URL(string: "url...")!)
request.httpMethod = "POST"
let postString = "actorGroup=\("Superhero")"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
DispatchQueue.main.async {
guard let data = data, error == nil else {
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
print("error : statusCode should be 200 but is \(httpStatus.statusCode)")
print("response = \(response)")
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode == 200 {
do {
let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as? [String: AnyObject]
guard let actorsJSON = json?["response"] as? [[String : AnyObject]] else {
return
}
} catch {
print("catch error")
}
}
}
}
task.resume()
}
func loadActors() -> [Actor] {
if let actors = actorsJSON as? [[String : AnyObject]] {
return actors.flatMap(Actor.init)
}
}
let actorsArray = loadActors()
class MasterViewController: UITableViewController {
var actorsList = [Actor]()
var detailViewController: DetailViewController? = nil
var objects = [Any]()
override func viewDidLoad() {
super.viewDidLoad()
actorsList = downloadActors()
print(actorsList)
結構演員如下:
struct Job {
let actorGroup: String
let actorName: String
}
extension Actor: JSONDecodable {
init?(JSON: [String : AnyObject]) {
guard let actorGroup = JSON["actorGroup"] as? String, let actorName = JSON["actorName"] as? String else {
return nil
}
self. actorGroup = actorGroup
self. actorName = actorName
}
}
非常混亂的代碼。 'do'塊中間的函數是什麼?你爲什麼要檢查'actorsJSON'兩次?計算的屬性是'let listActors ...',它應該可能是一個可選的綁定('如果let ...')。在Swift中,'.mutableContainers'完全是無稽之談。最後,一個JSON字典在Swift 3中是'[String:Any]'。' – vadian
'func loadActors'應該在哪裏?如果我把它放在'do'塊中,那麼我得到一個錯誤'未解決的標識符' – Luke
其實你根本不需要函數包裝器。 – vadian