Swift - 在词典中存储闭包

Ste*_*ell 15 closures dictionary swift

是否可以在词典中存储闭包(我们如何在词典中存储ObjC块)?例:

   data = [String:AnyObject]()
   data!["so:c0.onSelection"] = {() in
       Debug.log(.Debug, message: "Hello, World!")
   }
Run Code Online (Sandbox Code Playgroud)

Con*_*nor 19

你可以,但有一些限制.首先,函数类型不从AnyObject继承,也不共享公共基类.你可以有一本字典[String: () -> Void][String: (String) -> Int],但它们不能被存储在相同的字典.

我还必须使用一个typealias来定义字典,以便swift能够正确解析.这是一个基于您的代码段的示例.

typealias myClosure = () -> Void
var data: [String: myClosure]? = [String: myClosure]()
data!["so:c0.onSelection"] = {() -> Void in
    Debug.log(.Debug, message: "Hello, World!")
}
Run Code Online (Sandbox Code Playgroud)


Joã*_*nes 6

我有不同的方法

我创建了一个“holder”类来保存你的闭包,如下所示:

typealias SocialDownloadImageClosure = (image : UIImage?, error: NSError?) -> ()
typealias SocialDownloadInformationClosure = (userInfo : NSDictionary?, error: NSError?) -> ()


private class ClosureHolder
{
 let imageClosure:SocialDownloadImageClosure?
 let infoClosure:SocialDownloadInformationClosure?

 init(infoClosure:SocialDownloadInformationClosure)
 {
    self.infoClosure = infoClosure
 }
 init(imageClosure:SocialDownloadImageClosure)
 {
    self.imageClosure = imageClosure
 }
}
Run Code Online (Sandbox Code Playgroud)

然后我像这样制作字典:

var requests = Dictionary<String,ClosureHolder>()
Run Code Online (Sandbox Code Playgroud)

现在要向字典添加闭包,只需执行以下操作:

self.requests["so:c0.onSelection"] = ClosureHolder(completionHandler)
Run Code Online (Sandbox Code Playgroud)