Trying to get my code to compile from swift 3 to swift 4.

I'm using ObjectMapper : ObjectMapper FROM Github

And I'm getting the following 2 error messages

Cannot convert value of type 'Any?' to type 'AnyObject?' in coercion error Optional chain has no effect, expression already produces 'Any?'

let likesRequest = FBSDKGraphRequest(graphPath: "/me/likes", parameters: ["fields": "id, name, picture, user_likes", "after": after!])
let _ = likesRequest?.start() { (connection : FBSDKGraphRequestConnection?, result2 : Any?, error : Error?) -> Void in
let facebookLikes = Mapper<FacebookLikesListObject>().map(JSON: result2 as AnyObject?)

FacebookLikesListObject.swift

import UIKit

class FacebookLikesListObject: Mappable {
    var likes : [FacebookLikeObject]?
    var after : String?
    var before : String?

    required init?(map: Map) {

    }

    func mapping(map: Map) {
        likes <- map["data"]
        after <- map["paging.cursors.after"]
        before <- map["paging.cursors.before"]
    }
}```

2 Answers

0
Community On

Any is used for structs and/or classes whereas AnyObject is used for classes exclusively.

You can upcast from an AnyObject to Any safely, but you cannot do the opposite.

So, you can attempt to cast to AnyObject safely

   if let downCastedResult2 = result2 as? AnyObject{
      let facebooklikes = Mapper.map(JSON: downcastedResult2)
   }else{
     //fallback
   }

OR

You can force cast

    let facebookLikes = Mapper<FacebookLikesListObject>().map(JSON: result2 as! AnyObject)
0
Aman Pathak On

You can use the below code.

guard let objects = result2 as? AnyObject else { return }
let facebookLikes = Mapper<FacebookLikesListObject>().map(JSON: objects)