Reputation: 4572
Can I get a class by its name? For example:
class Foo {
}
class Bar {
}
let x = "Foo"
classByString(x) // need to return Foo
I want to use metaprogramming to reduce code maintenance.
Upvotes: 2
Views: 1742
Reputation: 66
You can use a NSClassFromString
:
if let anyObj : AnyObject.Type = NSClassFromString("MyAppName.MySwiftClassFoo") {
//call Foo
} else {
//call Bar
}
Upvotes: 5