0

I am having a difficulty with flatMap on returned json data. How can I Implement flatMap in the following code. I keep receiving an error: Computed property must have an explicit type

let task = URLSession.shared.dataTask(with: request) { data, response, error in

    DispatchQueue.main.async {

       if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode == 200 {

            do {
                let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String: Any]

                if let actors = json?["response"] as? [[String : Any]]  {
                    self.arrayActors = actors.flatMap(Actor.init)
                }

                self.tableView.reloadData()

            } catch {
                print("catch error")
            }


    } //end of if let httpStatus


}//end dispatch

}//end of task

The struct 'Actor' is here:

struct Actor {
    let actorName: String

}

extension Actor {
    init?(JSON: [String : Any]) {
        guard let actorName = JSON["actorName"] as? String else {
            return nil
        }
        self.actorName = actorName   
    }
}

Any help would be greatly appreciated!

Luke
  • 407
  • 2
  • 10
  • 22
  • Two things, missing `if` before `let actors = ...`. And in its true-case block, you cannot `return` anything from the async closure. – OOPer Jan 06 '17 at 23:32
  • I just added `if` and now I am getting an error: `'flatMap' produces '[SegmentOfResult.Iterator.Element]', not the expected contextual result type 'Void' (aka '()')` – Luke Jan 06 '17 at 23:41
  • As I wrote, you cannot `return` anything. Remove `return` and assign the result of `actors.flatMap(Actor.init)` to something used as the TableView's dataSource. – OOPer Jan 06 '17 at 23:44
  • I assigned the result to `arrayActors` and I also declared an empty array `arrayActors = [String : Any ]`. Now I am getting 2 errors: `'flatMap' produces '[SegmentOfResult.Iterator.Element]', not the expected contextual result type '[String : Any]'` and `Ambiguous reference to member 'subscript' ` – Luke Jan 06 '17 at 23:51
  • Why `[String: Any]`? – OOPer Jan 06 '17 at 23:54

1 Answers1

0

I just changed it to var actorsArray: [Actor] = [] and changed self.actorsArray = actors.flatMap(Job.init) and I worked!!! Thanks a lot @OOPer!!!

Luke
  • 407
  • 2
  • 10
  • 22