[swift-users] Instantiate Swift class from string

Jeremy Pereira jeremy.j.pereira at googlemail.com
Fri Dec 11 10:14:02 CST 2015


> On 10 Dec 2015, at 20:22, Matthew Davies via swift-users <swift-users at swift.org> wrote:
> 
> I'm building a URL router in which I'd like to pass a controller and a method. I don't want to instantiate all the controllers up front and pass the methods in as closures, nor do I want old controller instances still kept around. If there's a better way, I'm definitely open to any suggestions. I'm still learning the "Swift" way to do things.

The way I would do this is to define my controller interface with a protocol and then have a dictionary of the following type:

	[String: (Request) throws -> Controller]

where Controller is the protocol and Request is the HTTP request.

So you have a dictionary of URLs to functions (or closures) that create instances that conform to the Controller protocol. The closure takes a parameter of the HTTP request so it has the option of choosing the returned instance based on the method or headers or parameters in the request.

In my implementation, I took the path part of the URL and if it was in the dictionary it would use the returned closure to create the controller. If it wasn’t there, I chopped off the last path part and tried again and so on until I was left with “/“ which always maps to a controller.

The closure is allowed to throw so I could put something like this in for a path

    { _ in throw HTTPError(404) }

which would be handled further up the call chain by generating a 404 response.




More information about the swift-users mailing list