下载JSON并使用数据初始化Struct

时间:2017-01-03 12:35:06

标签: ios arrays struct swift3

我遇到以下代码问题。我正在下载JSON中的actor列表,我想用接收到的数据填充Struct Actor。一切都很好,直到我尝试对接收的数据进行flatMap并尝试初始化struct Actor。当我尝试编译代码时,我收到错误:Cannot assign value of type '()' to type [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 个答案:

没有答案