flatMap, Struct and JSON in Swift 3

885 views Asked by At

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!

1

There are 1 answers

0
Mike JS Choi On

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! })
    }
}