-1

I am having a problem with initializing Struct with JSON Data received from the URLRequest in Swift 3.

The protocol JSONDecodable:

protocol JSONDecodable {
            init?(JSON: [String : AnyObject])
        } 

The struct is as follows and it implements extension that conforms to JSONDecodable:

struct Actor {
    let ActorID: String
    let ActorName: String 
}

extension Actor: JSONDecodable {
    init?(JSON: [String : AnyObject]) {
        guard let ActorID = JSON["ActorID"] as? String, let ActorName = JSON["ActorName"] as? String else {
            return nil
        }
        self.ActorID = ActorID
        self.ActorName = ActorName

    }
}

Then I have the following code where I try to map an array of dictionaries to struct Actor. I think that I mix Swift 2 and Swift 3 syntax together.

 guard let actorsJSON = json?["response"] as? [[String : AnyObject]]  else {
                    return
                }

                return actorsJSON.flatMap { actorDict in
                    return Actor(JSON: actorDict)
                }

However, I get the following error: 'flatMap' produces '[SegmentOfResult.Iterator.Element]', not the expected contextual result type 'Void' (aka '()')

Any help would be greatly appreciated!

Luke
  • 407
  • 2
  • 10
  • 22
  • In the method in which you return the `flatMap` result, it seems as if you've forgetten to type annotate the return type in function signature. Now, you haven't shown us this function, but make sure that you function doesn't look like `func myFunction(some arguments) { ...` but rather `func myFunction(some arguments) -> [Actor] { ...`. – dfrib Dec 31 '16 at 23:33

1 Answers1

0

As @dfri mentioned, you haven't showed us your function signature but I'm also guessing you haven't specified the return type of the function.

This is how I would do it though

typealias JSONDictionary = [String: AnyObject]
extension Actor {
    func all(_ json: JSONDictionary) -> [Actor]? {
        guard let actorsJSON = json["response"] as? [JSONDictionary] else { return nil }
        return actorsJSON.flatMap(Actor.init).filter({ $0 != nil }).map({ $0! })
    }
}
Mike JS Choi
  • 1,081
  • 9
  • 19