Reputation: 605
I have a scenario where I've to cast an AnyObject to a dynamic type (available only at runtime). Is this possible with Swift? If yes, how would I do it?
To explain the scenario further, I have a function which has a completion block that returns the response or error from a service call. In the block, the success object is in fact an Array of AnyObject where the dynamicType of the object is that of the calling class.
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)
In the block objectOrNil is an array of a class X ([X]) where the X would be class invoking the service call. All the classes that call the method has a response dictionary object which is populated with the response after the service call is completed and the delegate invoked.
To handle a particular scenario, I need to intercept the service response (X.response) where X is objectOrNil[0] from within this block and do additional processing.
I'm able to see the class name when I do a
po objectOrNil[0].dynamicType
in the console, but am unable to cast the objectOrNil[0] to the right type X to fetch X.response. When I tried
po objectOrNil[0].response
I'm getting an error that response is ambiguous with NSURLResponse response. But
po objectOrNil[0].response as NSDictionary
returns the right JSON response in console during runtime (with breakpoint).
However the below code gives a compile time error that AnyObject does not have response attribute.
let responseDict = objectOrNil[0].response as NSDictionary
Can anyone guide me on how to cast to the dynamicType type and fetch the response dictionary for me to proceed?
Thanks
Upvotes: 1
Views: 368
Reputation: 285072
You could use a protocol
protocol Respondable {
var response : NSDictionary {get}
}
and then constrain the type of objectOrNil
to that protocol
someObject.callService(classObject, withCompletionBlock: {(objectOrNil : [Respondable]!, errorOrNil:NSError?) -> Void
Upvotes: 2