[swift-users] Instantiate Swift class from string

Jens Alfke jens at mooseyard.com
Thu Dec 10 11:23:00 CST 2015

> On Dec 10, 2015, at 7:26 AM, Harlan Haskins via swift-users <swift-users at swift.org> wrote:
> IIRC this isn’t possible because there’s no Runtime to query for classnames (it’s inherently unsafe anyway).

It’s not unsafe if you specify a base class/protocol that the loaded class must conform to.

> You might want to look into a better way of doing that you’re trying to do.

I disagree with “a better way” — “a workaround” is how I’d rephrase it. This kind of dynamism is often the best tool for the job, and a lot of Cocoa developers are frustrated by its absence in Swift. For example, there’s a series of blog posts from earlier this year by the highly respected Brent Simmons [NetNewsWire, MarsEdit, Glassboard, etc., currently at Omni]:

The workaround I’d suggest is a factory function that contains a switch statement that matches class names and returns newly initialized instances.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20151210/c2a6c979/attachment.html>

More information about the swift-users mailing list