简体   繁体   中英

Swift 3 Value of type 'Any?' has no member 'object'

I have updated swift 3 and I found many errors. This is one of them :

Value of type 'Any?' has no member 'object'

This is my code :

jsonmanager.post( "http://myapi.com",
                      parameters: nil,
                      success: { (operation: AFHTTPRequestOperation?,responseObject: Any?) in
                        if(((responseObject? as AnyObject).object(forKey: "meta") as AnyObject).object(forKey: "status")?.intValue == 200 && responseObject?.object(forKey: "total_data")?.intValue > 0){
                            let aa: Any? = (responseObject? as AnyObject).object(forKey: "response")

                            self.data = (aa as AnyObject).mutableCopy() 
                        }

New Error Update :

Optional chain has no effect, expression already produces 'Any?'

And

Cannot call value of non-function type 'Any?!'

It works well in previous version 7.3.1 swift 2.

This is json response :

{
 "meta":{"status":200,"msg":"OK"},
        "response":[""],
        "total_data":0
}

Unlike Swift 2, Swift 3 imports Objective-C's id as Any? instead of AnyObject? (see this Swift evolution proposal). To fix your error, you need to cast all of your variables to AnyObject . This may look something like the following:

jsonmanager.post("http://myapi.com", parameters: nil) { (operation: AFHTTPRequestOperation?, responseObject: Any?) in
    let response = responseObject as AnyObject?
    let meta = response?.object(forKey: "meta") as AnyObject?
    let status = meta?.object(forKey: "status") as AnyObject?
    let totalData = response?.object(forKey: "total_data") as AnyObject?
    if status?.intValue == 200 && totalData?.intValue != 0 {
        let aa = response?.object(forKey: "response") as AnyObject?
        self.data = aa?.mutableCopy() 
    }
}

您的responseObjectOptional (具体来说,是Any? ),因此您必须将其拆开以调用其方法或访问其属性,例如responseObject?.object(forKey: "meta")等等。现在,那些以前是非Optional值的框架现在是Optional ,尤其是在没有指定可空性限定符的情况下在Objective-C中使用它们的情况。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM