Swift中正确的块语法是什么 [英] What is the correct block syntax in Swift

查看:76
本文介绍了Swift中正确的块语法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我用Swift重写了一些Obj-C代码,偶然发现了一个使我抓狂的块. 我已经看过Apple提供的文档以及关于stackoverflow的一些其他资源.不幸的是,我找不到解决方案.我已经获得了我想在Swift中重新编写的obj-c代码.也许您可以帮我弄清楚该怎么做.我真的很感激!

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;

并被这样称呼:

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

到目前为止,我想到了这一点:

So far I came up with this:

var bridgeSearching : PHBridgeSearching = ...

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

推荐答案

如果块签名为

void (^PHBridgeSearchCompletionHandler) (NSDictionary *)

然后关闭应该是这样的:

then the closure should look like:

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

但是如果您知道字典中包含相同类型的对象,例如Int,并且键类型为String,那么您也可以将其写为

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.

这篇关于Swift中正确的块语法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆