What is the correct syntax for a block in Swift

so I rewrite Obj-C code in Swift and came across a block that is driving me crazy. I've already looked at the documentation provided by apple and some other resources here on stackoverflow. Unfortunately, no solution has yet been found. I have this obj-c code that I want to rewrite in Swift. Maybe you can help me figure out how to do this. I would really appreciate it!

- (void)startSearchWithCompletionHandler:(PHBridgeSearchCompletionHandler)completionHandler;

      

And it will turn out like this:

[self.bridgeSearch startSearchWithCompletionHandler:^(NSDictionary *bridgesFound) { ...

      

So far I have come up with this:

var bridgeSearching : PHBridgeSearching = ...

bridgeSearching.startSearchWithCompletionHandler { (bridgesFound: AnyObject!) -> PHBridgeSearchCompletionHandler in
}

      

+3


source to share


1 answer


If block signature

void (^PHBridgeSearchCompletionHandler) (NSDictionary *)

      

then the closure should look like this:

{ (bridgesFound: NSDictionary?) -> () in
    ...
}

      



but if you know the dictionary contains an object of the same type, say Int

and the key type is String

, you can also write it as

{ (bridgesFound: [String:Int]) -> () in
    ...
}

      

It is up to you to make this optional or not, depending on how you use it.

0


source







All Articles