Erik Erik - 1 year ago 97
Swift Question

Swift class introspection & generics

I am trying to dynamically create a

instance based type using generics, however I am encountering difficulty with class introspection.

Here are the questions:

  • Is there a Swift-equivalent to Obj-C's

  • Is there a way to instantiate a class using the
    result from

  • Is there a way to get
    or otherwise type information strictly from a generic parameter
    ? (Similar to C#'s

Answer Source

Well, for one, the Swift equivalent of [NSString class] is .self (see Metatype docs, though they're pretty thin).

In fact, NSString.class doesn't even work! You have to use NSString.self.

let s = NSString.self
var str = s()
str = "asdf"

Similarly, with a swift class I tried...

class MyClass {


let MyClassRef = MyClass.self

// ERROR :(
let my_obj = MyClassRef()

Hmm… the error says:

Playground execution failed: error: :16:1: error: constructing an object of class type 'X' with a metatype value requires an '@required' initializer

 <REPL>:3:7: note: selected implicit initializer with type '()'
 class X {

It took me a while to figure out what this means… turns out it wants the class to have a @required init()

class X {
    func me() {

    required init () {


let Y = X.self

// prints "asdf"

Some of the docs refer to this as .Type, but MyClass.Type gives me an error in the playground.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download