0

I'm having a problem with the following code. I'm downloading a list of actors in JSON and I want to populate Struct Actor with the received data. Everything works great until I try to flatMap on the received data and try to initialize the struct Actor. When I try to compile the code i get the error: Cannot assign value of type '()' to type [Actor]. The error corresponds to a line in viewDidLoad actorsList = downloadActors() Would anybody have any recommendation who to solve this?

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 is as follows:

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

    }
}
Luke
  • 407
  • 2
  • 10
  • 22
  • Your code doesn't make any sense `downloadActors` doesn't return anything, also `downloadActors` is making async call so if you return from function will not helps you, you need to create completion handler with your function, Also why are you adding function loadActors inside the `downloadActors`? – Nirav D Jan 03 '17 at 12:40
  • Yesterday I made a few suggestions. Have you ever tried one of them? – vadian Jan 03 '17 at 13:17
  • I just added dispatch and I moved the code of loadActors after the function downloadActors. – Luke Jan 03 '17 at 13:20
  • @vadian Yes, I did made changes. I implemented if let.. which seemed to help. Still can't get it working though. – Luke Jan 03 '17 at 13:21
  • Your code is still very confusing and hard to read because it's not formatted at all. Which class does `downloadActors()` belong to? Nirav's comment contains the error reason. You will run into the next problem because the `init` method is supposed to be `Actor(JSON:... )`. Once again JSON dictionary is `[String:Any]` in Swift 3, the second type check of `actorsJSON` is redundant and `.mutableContainers` option is meaningless. Finally you should conform to the naming convention that variable names start with a lowercase letter. – vadian Jan 03 '17 at 13:33
  • @vadian The downloadActors() function is defined in top level, right above class MasterViewController. – Luke Jan 03 '17 at 17:46
  • Don't do that. All custom code is supposed to be encapsulated in a class or struct. – vadian Jan 03 '17 at 18:18

0 Answers0