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
}
});
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'.
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:
Which allows me to define a function with an inline delegate:
And the code to test it out in a playground:
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.