[swift-users] Instantiate Swift class from string

Brent Royal-Gordon brent at architechies.com
Thu Dec 10 18:12:07 CST 2015


(Sorry for the repeat, Matthew.)

> Can you clarify a bit on that? So, what you're saying is to generate routing code based off the DSL router I've written?

Yes, unless you can modify your DSL so you can directly provide your controller classes, you’ll probably need to generate code.

By “provide your controller classes”, I mean that you could make a routes file which looked something like this (this routing syntax is loosely inspired by Rails):

	import MyFramework.Router
	
	// UsersController.self is an instance which represents the UsersController class.
	// It’s of type UsersController.Type, which might (for instance) be a subtype of WebController.Type, etc.
	Router.root.resources(UsersController.self, path: “users”) { users in
		users.resources(PostsController.self, path: “posts”) { posts in
			// PostsController.comments is a way to retrieve a closure which calls PostsController’s comments() instance method.
			// You use it by saying something like `myClosure(myControllerInstance)(arg1, arg2, etc)`.
			posts.get(PostsController.comments, path: “comments”)
		}
		users.resources(CommentsController.self, path: “comments”)
	}

Note that in all cases you pass instances, not names, to your routing APIs. This allows you to write code that can work with any compatible class or method without any danger of trying to use a class or method that doesn’t exist.

But using this approach limits the flexibility of your routing DSL’s design. For instance, you can’t just take the string “users” and infer that you should use UsersController. If you want that sort of more sophisticated behavior, you’re going to need to generate Swift code instead.

-- 
Brent Royal-Gordon
Architechies



More information about the swift-users mailing list