Just For Fun

Use Clousre for Object Initializing

Today I have spent some time to dig into a few open source Swift XML parsing libs. One lib called SWXMLHash have a set of familiar API inspired from SwiftyJSON caught my eye.

After some performance and memory footprint benchmark test. I have gave up using the SWXMLHash lib as a essential part of my new project.

But the main Object initial API of SWXMLHash have gave me a mind blow inspiring. I wish record the feeling and share with you.

The basic form of SWXMLHash initial API is like this:

let xml = SWXMLHash.config {
              config in
              config.shouldProcessLazily = true
              // set any config options here
          }.parse(xmlToParse)

You can see instead give the config method a configuration object instance or a Dictionary , the above code passed a closure to the config method.

This style is very elegance and practice in my view. And having revealed the versatility and flexibility of closure in Swift language.

The implementation of config method as following:

class public func config(_ configAction: (SWXMLHashOptions) -> Void) -> SWXMLHash {
        let opts = SWXMLHashOptions()
        configAction(opts)
        return SWXMLHash(opts)
    }   

The solo argument of closure function is a raw SWXMLHashOptions instance. The closure function body add some configuration to the instance. Because the configuration process is in a function body, you can do so many magic thing even network request before you finally decide how to configure the very object.

There are another fundamental Swift language knowledge in above code snippet. “Object instance is alway pass to function as reference”.

Leveraging Closure and reference object parameter passing we are having a wider mind about how to initial an Object , a lib or your next project.