1. <tfoot id='b88JY'></tfoot>

        <bdo id='b88JY'></bdo><ul id='b88JY'></ul>
    2. <small id='b88JY'></small><noframes id='b88JY'>

    3. <legend id='b88JY'><style id='b88JY'><dir id='b88JY'><q id='b88JY'></q></dir></style></legend>
      <i id='b88JY'><tr id='b88JY'><dt id='b88JY'><q id='b88JY'><span id='b88JY'><b id='b88JY'><form id='b88JY'><ins id='b88JY'></ins><ul id='b88JY'></ul><sub id='b88JY'></sub></form><legend id='b88JY'></legend><bdo id='b88JY'><pre id='b88JY'><center id='b88JY'></center></pre></bdo></b><th id='b88JY'></th></span></q></dt></tr></i><div id='b88JY'><tfoot id='b88JY'></tfoot><dl id='b88JY'><fieldset id='b88JY'></fieldset></dl></div>

      在 Swift 中使用闭包实现委托?

      Implement Delegate with Closure in Swift?(在 Swift 中使用闭包实现委托?)

          <small id='qKWnt'></small><noframes id='qKWnt'>

          • <i id='qKWnt'><tr id='qKWnt'><dt id='qKWnt'><q id='qKWnt'><span id='qKWnt'><b id='qKWnt'><form id='qKWnt'><ins id='qKWnt'></ins><ul id='qKWnt'></ul><sub id='qKWnt'></sub></form><legend id='qKWnt'></legend><bdo id='qKWnt'><pre id='qKWnt'><center id='qKWnt'></center></pre></bdo></b><th id='qKWnt'></th></span></q></dt></tr></i><div id='qKWnt'><tfoot id='qKWnt'></tfoot><dl id='qKWnt'><fieldset id='qKWnt'></fieldset></dl></div>
            <legend id='qKWnt'><style id='qKWnt'><dir id='qKWnt'><q id='qKWnt'></q></dir></style></legend>
            <tfoot id='qKWnt'></tfoot>
              • <bdo id='qKWnt'></bdo><ul id='qKWnt'></ul>

                  <tbody id='qKWnt'></tbody>
                本文介绍了在 Swift 中使用闭包实现委托?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

                问题描述

                Suppose I'm using Swift and calling a method in the framework that is expecting a delegate.

                Is it possible to provide a closure and implement the delegate right there inline?

                I'm hoping to be able to use this like anonymous classes in Java. For Example:

                let cnx:NSURLConnection = NSURLConnection(request: request, delegate: {
                     func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
                         //append data
                     }
                     func connectionDidFinishLoading(connection: NSURLConnection){
                         //all done
                     }
                });
                

                解决方案

                You can't define an anonymous class, but you can define a local class that works very similarly. I've actually migrated away from the inline class approach as the REPL seems to have problems with it even though it seems to be fine with the compiler. The approach I'm now using is to define a glue class which forwards methods to closures defined in the init, so it all feels very natural.

                The URLConnectionDataDelegate is defined as:

                class GreenUrlConnectionDataDelegate: NSObject, NSURLConnectionDataDelegate {
                    var didFinishLoading:()->()
                    var didReceiveResponse:((NSURLResponse!)->())?
                    var didReceiveData:((NSData!)->())?
                    var didFailWithError:((NSError!)->())?
                
                    func connectionDidFinishLoading(conn:NSURLConnection!) {
                        didFinishLoading()
                    }
                
                    func connection(conn:NSURLConnection!, didReceiveResponse response:NSURLResponse!) {
                        didReceiveResponse?(response)
                    }
                
                    func connection(conn:NSURLConnection!, didReceiveData data:NSData!) {
                        didReceiveData?(data)
                    }
                
                    func connection(conn:NSURLConnection!, didFailWithError error:NSError!) {
                        didFailWithError?(error)
                    }
                
                    init(
                        didFinishLoading:@escaping ()->(),
                        didReceiveResponse:@escaping ((NSURLResponse!)->())? = nil,
                        didReceiveData:@escaping ((NSData!)->())? = nil,
                        didFailWithError:@escaping ((NSError!)->())? = nil
                    ) {
                        self.didFinishLoading = didFinishLoading
                        self.didReceiveResponse = didReceiveResponse
                        self.didReceiveData = didReceiveData
                        self.didFailWithError = didFailWithError
                    }
                }
                

                Which allows me to define a function with an inline delegate:

                func downloadUrl(string:String, completion:(data:NSData?, error:NSError?) -> ()) {
                    let url = NSURL(string:string)
                    let request = NSURLRequest(URL: url)
                    var received:NSMutableData! = nil
                    let conn = NSURLConnection(request: request, delegate: GreenUrlConnectionDataDelegate(
                            didFinishLoading:{
                                completion(data:received, error:nil)
                            },
                            didReceiveResponse:{response in
                                if let capacity = response?.expectedContentLength {
                                    if capacity > 0 {
                                        received = NSMutableData(capacity: Int(capacity))
                                    }
                                    else {
                                        received = NSMutableData()
                                    }
                                }
                            },
                            didReceiveData:{data in
                                if data != nil {
                                    received.appendData(data)
                                }
                            },
                            didFailWithError:{error in
                                completion(data:nil, error:error)
                            }
                        )
                    )
                }
                

                And the code to test it out in a playground:

                downloadUrl("http://www.google.com") {
                    (data:NSData?, error:NSError?) -> () in
                    println("completion")
                    println("data.size: (data?.length)")
                    println("error: (error?.localizedDescription)")
                }
                
                XCPSetExecutionShouldContinueIndefinitely()
                

                You could conceivably even embed the glue class into an extension to the class requiring the delegate, although I haven't tried that out yet.

                这篇关于在 Swift 中使用闭包实现委托?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

                本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

                相关文档推荐

                reloadData() of UITableView with Dynamic cell heights causes jumpy scrolling(具有动态单元格高度的 UITableView 的 reloadData() 导致跳跃滚动)
                How to format localised strings in Swift?(如何在 Swift 中格式化本地化字符串?)
                Why do we need to set delegate to self? Why isn#39;t it defaulted by the compiler?(为什么我们需要将委托设置为自我?为什么编译器不默认它?)
                set delegate and datasource of uitableview programmatically in Swift(在 Swift 中以编程方式设置 uitableview 的委托和数据源)
                How can I wait for a NSURLConnection delegate to finish before executing the next statement?(在执行下一条语句之前,如何等待 NSURLConnection 委托完成?)
                Swift delegate beetween two VC without segue(两个没有 segue 的 VC 之间的 Swift 委托)

                  <tbody id='apQad'></tbody>

                • <bdo id='apQad'></bdo><ul id='apQad'></ul>
                      • <i id='apQad'><tr id='apQad'><dt id='apQad'><q id='apQad'><span id='apQad'><b id='apQad'><form id='apQad'><ins id='apQad'></ins><ul id='apQad'></ul><sub id='apQad'></sub></form><legend id='apQad'></legend><bdo id='apQad'><pre id='apQad'><center id='apQad'></center></pre></bdo></b><th id='apQad'></th></span></q></dt></tr></i><div id='apQad'><tfoot id='apQad'></tfoot><dl id='apQad'><fieldset id='apQad'></fieldset></dl></div>

                        1. <tfoot id='apQad'></tfoot>

                        2. <legend id='apQad'><style id='apQad'><dir id='apQad'><q id='apQad'></q></dir></style></legend>

                          <small id='apQad'></small><noframes id='apQad'>