简体   繁体   中英

What is the correct block syntax in Swift

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
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM