在Swift中实现闭包委托? [英] Implement Delegate with Closure in Swift?

查看:66
本文介绍了在Swift中实现闭包委托?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我正在使用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?

我希望能够像Java中的匿名类一样使用它。例如:

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


推荐答案

您无法定义匿名类,但您可以可以定义一个非常相似的本地类。实际上,我已经从内联类方法迁移了,因为REPL似乎有问题,即使编译器看起来还不错。我现在使用的方法是定义一个粘合类,该类将方法转发给init中定义的闭包,因此感觉很自然。

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.

URLConnectionDataDelegate定义为:

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中实现闭包委托?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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