Implement Delegate with Closure in Swift?

2019-03-18 21:49发布

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

2条回答
乱世女痞
2楼-- · 2019-03-18 22:21

Closures are not the same as anonymous classes, so no, I don't think you will find a pattern that achieves what you wish. Your uses braces in a similar style to JavaScript or C# to create an object instance. This isn't valid Swift.

There are already techniques for implementing delegates without creating a class instance. See for example the ReactiveCocoa 'delegate pattern'.

查看更多
我命由我不由天
3楼-- · 2019-03-18 22:26

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:()->(),
        didReceiveResponse:((NSURLResponse!)->())? = nil,
        didReceiveData:((NSData!)->())? = nil,
        didFailWithError:((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:{
                if let capacity = $0?.expectedContentLength {
                    if capacity > 0 {
                        received = NSMutableData(capacity: Int(capacity))
                    }
                    else {
                        received = NSMutableData()
                    }
                }
            },
            didReceiveData:{
                if $0 != nil {
                    received.appendData($0)
                }
            },
            didFailWithError:{
                completion(data:nil, error:$0)
            }
        )
    )
}

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.

查看更多
登录 后发表回答