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


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)