问题
So I am using the Salesforce SDK and built bridging headers for the entire SDK.
They provide a block syntax which hasn't translated into the most usable code. For instance,
func sendRESTRequest(request: SFRestRequest!, failBlock: SFRestFailBlock!, completeBlock: AnyObject!)
The complete block is AnyObject!. I was able to get around this with
var block : @objc_block (dataResponse :AnyObject!) -> Void = { dataResponse in //I handle the response}
restService.sendRESTRequest(request, failBlock: { (error :NSError!) -> Void in
}, completeBlock: unsafeBitCast(block, AnyObject.self))
So far this works fine. However, now I am trying to build unit testing for this code. I have created a mock class for SFRestAPI which is the class where the function "sendRESTRequest" resides. For testing purposes, I am trying to mock out the completeBlock: parameter by passing mock "data" that would be returned from the REST service.
class MockSFRestAPI : SFRestAPI {
override func sendRESTRequest(request: SFRestRequest!, failBlock: SFRestFailBlock!, completeBlock: AnyObject!) {
//Convert complete block into a closure and pass in some test data
}
}
The issue is, I am unable to cast AnyObject! to a block like I was able to cast the block to AnyObject like above.
Some of my attempts have been:
var block = completeBlock as @objc_block (AnyObject! -> Void)
var block2: (AnyObject! -> Void) = unsafeBitCast(completeBlock, (@objc_block (AnyObject! -> Void)))
There have been many more attempts, but these are the only two that seem relatively sane. So, is this possible in Swift? The issue seems to be that I cannot provide a closure "type" to the second parameter of the unsafeBitCast method. I want to turn it into a closure so I can call it in my mock method and pass in some fake data.
回答1:
The best way to handle this situation is to create your own typealias for your block:
typealias MyFunBlock = @objc_block (dataResponse :AnyObject!) -> Void;
Then you can use that to unsafebitcast:
var block: MyFunBlock = unsafeBitCast(completeBlock, MyFunBlock.self) as MyFunBlock;
来源:https://stackoverflow.com/questions/26738732/swift-cast-anyobject-to-block