【问题标题】:Swift - Store Closures in DictionarySwift - 在字典中存储闭包
【发布时间】:2014-08-05 01:58:42
【问题描述】:

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

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

【问题讨论】:

    标签: dictionary swift closures


    【解决方案1】:

    可以,但有一些限制。首先,函数类型不继承自 AnyObject 并且不共享公共基类。 [String: () -> Void][String: (String) -> Int] 可以有一个字典,但它们不能存储在同一个字典中。

    我还必须使用类型别名来定义字典,以便 swift 能够正确解析。这是一个基于您的 sn-p 的示例。

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

    【讨论】:

      【解决方案2】:

      我有不同的方法

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

      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
       }
      }
      

      然后我像这样制作字典:

      var requests = Dictionary<String,ClosureHolder>()
      

      现在要为字典添加一个闭包,只需这样做:

      self.requests["so:c0.onSelection"] = ClosureHolder(completionHandler)
      

      【讨论】:

        【解决方案3】:

        Connor 是对的,我确实尝试了很多方法将变量和闭包存储在同一个字典中,但我失败了,无法解析出来,swift 反编译器会抛出错误:

        "Command failed due to signal: Segmentation fault: 11" (the hell is it?!)
        

        例如:

        //This won't work
        var params:[String: Any] = ["x":100, "onFoundX": {println("I found X!")}]
        if var onFoundX: (()->Void) = params["onFoundX"] as? (()->Void) {
            onFoundX()
        }
        
        //This should work by separate into 2 dictionaries and declare the "typealias" obviously
        var params:[String: Any] = ["x":"100"}]
        var events:[String: (()->Void)] = ["onFoundX": {println("I found X!")]
        
        if var onFoundX: (()->Void) = events["onFoundX"] as? (()->Void) {
            onFoundX() // "I found X!"
        }
        
        if var x = events["x"] as? String {
            println(x) // 100
        }
        

        我希望 Swift 将来会允许这种情况发生..

        干杯!

        【讨论】:

          【解决方案4】:

          这个简单的例子帮助我理解了更多:

          //Init dictionary with types (i.e. String type for key, Closure type for value):
          var myDictionary: [String: ()->(String)] = [:]
          
          //Make a closure that matches the closure signature above and assign to variable (i.e. no parameter and returns a String):
          let sayHello: () -> (String) = {
              return "Hello!"
          }
          
          //Add closure to dictionary with key:
          myDictionary["myFunc"] = sayHello
          
          //Access closure by known key and call it:
          myDictionary["myFunc"]!() //"Hello!"
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2014-11-12
            • 2014-08-29
            • 1970-01-01
            • 1970-01-01
            • 2020-11-02
            • 2015-06-07
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多