Swift Cast AnyObject to Block [英] Swift Cast AnyObject to Block
问题描述
所以我使用的是Salesforce SDK,并为整个SDK建立了桥接头。
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!)
完整的块是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))
到目前为止这个工作正常。然而,现在我试图为这个代码构建单元测试。我为SFRestAPI创建了一个模拟类,它是函数sendRESTRequest所在的类。为了测试目的,我试图通过传递从REST服务返回的mockdata来模拟completeBlock:参数。
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
}
}
问题是,我无法投射AnyObject!
The issue is, I am unable to cast AnyObject! to a block like I was able to cast the block to AnyObject like above.
我的一些尝试是:
var block = completeBlock as @objc_block (AnyObject! -> Void)
var block2: (AnyObject! -> Void) = unsafeBitCast(completeBlock, (@objc_block (AnyObject! -> Void)))
还有更多的尝试,只有两个似乎相对健全。那么,这是可能在Swift吗?问题似乎是,我不能提供一个闭包类型到unsafeBitCast方法的第二个参数。我想把它变成一个闭包,所以我可以在我的mock方法中调用它,并传递一些假数据。
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.
推荐答案
最好的方式来处理这种情况是为你的块创建自己的typealias:
The best way to handle this situation is to create your own typealias for your block:
typealias MyFunBlock = @objc_block (dataResponse :AnyObject!) -> Void;
然后,您可以将其用于unsafebitcast:
Then you can use that to unsafebitcast:
var block: MyFunBlock = unsafeBitCast(completeBlock, MyFunBlock.self) as MyFunBlock;
这篇关于Swift Cast AnyObject to Block的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!