What is the correct block syntax in Swift

眉间皱痕 提交于 2019-12-10 21:14:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!