I know it is possible to pass class type to a function in swift:
func setGeneric(type: T.Type){ }
setGeneric(Int.self)
But how we can
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()
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 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.
Yes, this is possible. The problem here is that you say your function returns a generic T.type
, but you always return Int.type
. Since T is not always an Int, the compiler raises an error.