我遇到以下代码问题。我在JSON中下载了一个actor列表,我想用接收到的数据填充Struct Actor。一切都很好,直到我尝试对接收的数据进行flatMap并尝试初始化struct Actor。当我尝试编译代码时,我得到错误:无法分配类型的值'()'输入[Actor]。该错误对应于viewDidLoad中的一行actorsList = downloadActors()任何人都有任何建议由谁来解决这个问题?
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 Actors如下:
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
}
}
答案 0 :(得分:0)
let listActors = actorsJSON as? [[String : AnyObject]] {
应该是:
if let listActors = actorsJSON as? [[String : AnyObject]] {
修改:有关详细信息,我想添加Vadian's评论:
非常令人困惑的代码。 阻止中间的功能是什么?为什么要两次打字actorsJSON
?计算属性为let listActors
...应该可能是可选绑定(如果让...)。进一步.mutableContainers
在Swift中完全是胡说八道。最后,Swift 3中的JSON字典为[String:Any]
。