问题
so I am rewriting some Obj-C code in Swift and stumbled across a block which drives me crazy. I've already had a look at the documentation provided by apple and some other resources here on stackoverflow. Unfortunately, I couldn't find the solution, yet. IÄve got that piece of obj-c code which I want to re-write in Swift. Maybe you can help me figuring out how to do that. I'd really appreciate it!
- (void)startSearchWithCompletionHandler:(PHBridgeSearchCompletionHandler)completionHandler;
And gets called like this:
[self.bridgeSearch startSearchWithCompletionHandler:^(NSDictionary *bridgesFound) { ...
So far I came up with this:
var bridgeSearching : PHBridgeSearching = ...
bridgeSearching.startSearchWithCompletionHandler { (bridgesFound: AnyObject!) -> PHBridgeSearchCompletionHandler in
}
回答1:
If the block signature is
void (^PHBridgeSearchCompletionHandler) (NSDictionary *)
then the closure should look like:
{ (bridgesFound: NSDictionary?) -> () in
...
}
but if you know the dictionary contains object of the same type, let's say Int
, and the key type is String
, then you can also write it as
{ (bridgesFound: [String:Int]) -> () in
...
}
Up to you whether to make it optional or not, depending on how you are using it.
来源:https://stackoverflow.com/questions/25481372/what-is-the-correct-block-syntax-in-swift