macabeus
macabeus

Reputation: 4572

Get class by name

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

Answers (1)

Marcus Vinicius
Marcus Vinicius

Reputation: 66

You can use a NSClassFromString:

if let anyObj : AnyObject.Type = NSClassFromString("MyAppName.MySwiftClassFoo") {
   //call Foo
} else {
   //call Bar
}

Upvotes: 5

Related Questions