无法转换类型Any?要键入AnyObject?从swift 3转换为swift 4时

问题描述 投票:0回答:2

试图让我的代码从swift 3编译成swift 4。

我正在使用ObjectMapper:ObjectMapper FROM Github

我收到以下2条错误消息

无法转换'Any?'类型的值输入'AnyObject?'在强制错误中可选链没有效果,表达式已经产生'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"]
    }
}```
ios swift xcode facebook-graph-api
2个回答
0
投票

Any用于结构和/或类,而AnyObject专用于类。

你可以安全地从AnyObject升级到Any,但你不能做相反的事情。

因此,您可以尝试安全地转换为AnyObject

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

要么

你可以强迫施法

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

0
投票

您可以使用以下代码。

guard let objects = result2 as? AnyObject else { return }
let facebookLikes = Mapper<FacebookLikesListObject>().map(JSON: objects)
© www.soinside.com 2019 - 2024. All rights reserved.