37

I'd like to do something like this:

func doSomething(a: AnyObject, myType: ????)
{
   if let a = a as? myType
   {
       //…
   }
}

In Objective-C the class of class was Class

juhan_h
  • 3,965
  • 4
  • 29
  • 35
  • You'll want to use generics with a method input of type `T.Type`, you can then cast to `T` – see for example [this Q&A](http://stackoverflow.com/questions/37216240/generic-function-taking-a-type-name-in-swift) – Hamish Sep 12 '16 at 11:04

1 Answers1

87

You have to use a generic function where the parameter is only used for type information so you cast it to T:

func doSomething<T>(_ a: Any, myType: T.Type) {
    if let a = a as? T {
        //…
    }
}

// usage
doSomething("Hello World", myType: String.self)

Using an initializer of the type T

You don’t know the signature of T in general because T can be any type. So you have to specify the signature in a protocol.

For example:

protocol IntInitializable {
    init(value: Int)
}

With this protocol you could then write

func numberFactory<T: IntInitializable>(value: Int, numberType: T.Type) -> T {
    return T.init(value: value)
}

// usage
numberFactory(value: 4, numberType: MyNumber.self)
Community
  • 1
  • 1
Qbyte
  • 12,753
  • 4
  • 41
  • 57
  • how I call the constructor? – Augusto Mar 29 '18 at 03:00
  • @Augusto Please see my updated answer. I hope this helps. – Qbyte Mar 30 '18 at 00:15
  • Let me explain my problem: I have a Database with some tables, for each table I have a class ( for each object, like product, person, customers...) I wants create a generic function to read all records from database, because this I want use the T (type class) for create a list of these objects. I don't know how I set the type class to create a new object. My constructors receive a dictonary of attributes like parameter. – Augusto Mar 30 '18 at 15:23
  • 1
    @Augusto I think "Rob" answered it perfectly in your question https://stackoverflow.com/q/49577256/4780031 which is almost my example. – Qbyte Mar 30 '18 at 21:11