20

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
     }
});
rmaddy
  • 314,917
  • 42
  • 532
  • 579
bgolson
  • 3,460
  • 5
  • 24
  • 41

2 Answers2

32

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.

joshperry
  • 41,167
  • 16
  • 88
  • 103
David Berry
  • 40,941
  • 12
  • 84
  • 95
  • 2
    Have you tried this anywhere yet? I just implemented a UITabBarDelegate using this pattern and everything compiles fine but the app crashes whenever a tab is selected. As soon as I went back to using "self" for the delegate everything works as usual, but it's so messy when you implement a lot of callbacks on one screen. Thanks for the help! – bgolson Jun 12 '14 at 21:39
  • 1
    I haven't used it with the class embedded in the function because the REPL crashes on it. I have a version of it that I'll upload here in a few minutes that's based on a class with closures that works fine in the playgrounds. – David Berry Jun 12 '14 at 21:46
  • Wow, this looks really promising! Can't wait to try it out tomorrow! Thanks so much David! – bgolson Jun 13 '14 at 05:07
  • 2
    Oh, this is a good pattern. This allows for designing architectures using the delegate pattern while still being able to kind of substitute it with closures. Very nice. – Lars Blumberg Dec 11 '15 at 15:09
0

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'.

ColinE
  • 68,894
  • 15
  • 164
  • 232