[swift-users] Instantiate Swift class from string

Matthew Davies daviesgeek at gmail.com
Thu Dec 10 17:43:22 CST 2015


I could do that, and that would work, but I figured out a way of doing
this.

import Foundation

protocol Controller {
init()
}

class Main : Controller {
required init() {}
func index() -> String {
return "INDEX"
}
}

let inst = Main()
let method = Main.index
method(inst)

func run<T>(ctrl: Controller.Type, method: (T -> () -> String)) {
let inst = ctrl.init()
let handler = method(inst as! T)
print(handler())
}

I've posted the source code for the router here:
https://github.com/daviesgeek/swiftrouter
It's very much incomplete, so keep that in mind when you're looking at it.
The relevant code is here:
https://github.com/daviesgeek/swiftrouter/blob/master/Sources/Router.swift#L19

Thanks so much for everyone's help!



*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 Thu, Dec 10, 2015 at 3:25 PM, Jens Alfke <jens at mooseyard.com> wrote:

>
> On Dec 10, 2015, at 1:01 PM, Matthew Davies via swift-users <
> swift-users at swift.org> wrote:
>
>   func get(url: String, ctrl: Controller.Type, method: String) {
>     let inst = ctrl.init()
> *    // Run the method that is passed in here*
>   }
>
>
> Since HTTP only has a handful of standard methods/verbs, you can just
> define a Swift method for each one in your protocol (get, put, delete,
> etc.) and use a switch statement on the `method` parameter to dispatch to
> the right one.
>
> This is a case where you wouldn’t want to use dynamic lookup anyway, since
> the method name you’d be looking up and calling would be chosen by the
> remote client. That’s the sort of thing that’s just begging to be exploited
> (I.e. someone opens a TCP socket and sends “getWithoutCheckingAuth
> /admin/secretdata.txt HTTP/1.1”…)
>
> —Jens
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20151210/40d4ad49/attachment.html>


More information about the swift-users mailing list