Swift 3类型的价值'任何?'没有会员'对象'

时间:2016-09-15 02:57:56

标签: ios swift swift3

我更新了swift 3,发现了很多错误。这是其中之一:

  

类型的价值'任何?'没有会员'对象'

这是我的代码:

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

新错误更新:

  

可选链无效,表达式已生成'任何?'

  

无法调用非功能类型的值'任何?!'

在以前的版本7.3.1 swift 2中运行良好。

这是json回应:

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

2 个答案:

答案 0 :(得分:18)

与Swift 2不同,Swift 3将Objective-C的id导入Any?而不是AnyObject?(参见this Swift evolution proposal)。要修复错误,您需要将所有变量强制转换为AnyObject。这可能类似于以下内容:

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

答案 1 :(得分:0)

您的responseObjectOptional(具体而言是Any?),因此您必须打开它才能调用其方法或访问其属性,例如responseObject?.object(forKey: "meta"),框架中有几个地方过去非Optional的值现在是Optional,特别是在没有指定的可空性限定符的情况下在Objective-C中使用它们的地方。