[swift-users] Instantiate Swift class from string
Matthew Davies
daviesgeek at gmail.com
Fri Dec 11 12:59:47 CST 2015
The problem is still, how would I call the controller method? I still can't
instantiate a new instance of the controller and call a given method on the
instance.
I was able to partially get this working, but I realized that I still can't
instantiate a new controller on each request. I can't figure out a good way
to store the class method
*Matthew Davies*
Junior Developer, GeoStrategies <http://geostrategies.com>
Director of Photography, OffBlock Films <http://offblockfilms.com>
209-225-3246 <209-225.3246> | 209-202-3284 | daviesgeek at gmail.com |
daviesgeek.com
<http://facebook.com/daviesgeek> <http://us.linkedin.com/in/daviesgeek>
<http://twitter.com/daviesgeek> <http://daviesgeek.com/feed.xml>
<http://github.com/daviesgeek>
On Fri, Dec 11, 2015 at 8:14 AM, Jeremy Pereira <
jeremy.j.pereira at googlemail.com> wrote:
>
> > 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.
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20151211/18e9fdac/attachment.html>
More information about the swift-users
mailing list