Swift: how to return class type from function Swift: how to return class type from function ios ios

Swift: how to return class type from function


You can return any type you want.

func getTypeOfInt()  -> Int.Type  { return Int.self  }func getTypeOfBool() -> Bool.Type { return Bool.self }

If the type is not determined from arguments or if the return is constant, there is no need to introduce a generic T type.


It works when I modify your function like this:

func getGeneric<T>(object: T) -> T.Type {    return T.self}getGeneric(0)    // Swift.Int


You can force the downcast (as!) as below

func getGeneric<T>() -> T.Type {  return Int.self as! T.Type} 

But out of the function scope, you need to indicate the returned type:

var t:Int.Type = getGeneric()