我有一个场景,我将AnyObject转换为动态类型(仅在运行时可用)。 Swift可以实现吗?如果是的话,我该怎么做?
为了进一步解释这个场景,我有一个函数,它有一个完成块,可以从服务调用中返回响应或错误。在块中,success对象实际上是AnyObject的Array,其中object的dynamicType是调用类的dynamicType。
someObject.callService(classObject, withCompletionBlock: {(objectOrNil : [AnyObject]!, errorOrNil:NSError?) -> Void in
if(errorOrNil != nil) { self.delegate.didFailWithError(errorOrNil)
}
else {
// Here objectOrNil is during runTime an Array of class X
// X.response gives the response JSON
// In a particular scenario, I need to intercept the response before the delegate
self.delegate.didReceiveResponse(objectOrNil)
}
}, withProgressBlock: nil)
在块中,objectOrNil是一个类X([X])的数组,其中X将是调用服务调用的类。调用该方法的所有类都有一个响应字典对象,该对象在服务调用完成并调用委托后填充响应。
为了处理特定场景,我需要拦截服务响应(X.response),其中X是此块中的objectOrNil [0]并执行其他处理。
当我做
时,我能够看到班级名称po objectOrNil[0].dynamicType
在控制台中,但无法将objectOrNil [0]强制转换为正确的类型X以获取X.response。我试过的时候
po objectOrNil[0].response
我收到的错误是NSURLResponse响应的响应不明确。但是
po objectOrNil[0].response as NSDictionary
在运行时(带断点)在控制台中返回正确的JSON响应。
但是,下面的代码给出了编译时错误,AnyObject没有响应属性。
let responseDict = objectOrNil[0].response as NSDictionary
任何人都可以指导我如何转换为dynamicType类型并获取响应字典以供我继续使用吗?
谢谢
答案 0 :(得分:2)
您可以使用协议
protocol Respondable {
var response : NSDictionary {get}
}
然后将objectOrNil
的类型约束到该协议
someObject.callService(classObject, withCompletionBlock: {(objectOrNil : [Respondable]!, errorOrNil:NSError?) -> Void