How to use type of a variable to declare another variable

In Swift, I can get the type of a variable with type(of: myvariable), but how can I use this type to declare another variable.

Expected:

let a = 1
typealias typeofA = type(of: a) // expected: Int
let b: typeofA

However, the statement typealias typeofA = type(of: a) has a compile error. So how can I achieve my goal?

There's no way to do that. type(of:) is a normal function returning a metatype variable. You can't use variables where type is expected, and there's currently no way to define a type that is the same as that variable, well, other than the usual let b = a.

All right. In my opinion, since the type can be inferred and decided in compile time, why we can't use the type to do something?

In other language like TypeScript, we can do that like:

var a = 1
type typeofA = typeof a
var b: typeofA = 2

Note that type(of:) returns the dynamic type of a variable.

You are correct that we could something that gives you the static type, but since it is knowable at compile time, it is also knowable to you, so this would not enable anything that you can't already write today. There is no such feature in the language today.

It make sense.

Don't know whether Swift will support this feature in the future. When the type is complex, I really need such feature instead of annotating by myself.:joy:

Thank both of you @Lantua @xwu for your reply.

1 Like

Hi Ray,

You can build something like this easily if you want even for the standard types (Int, Double, String). Looks like you want to do so only for the custom types you are defining. And this can be done using something like below with help of a protocol

protocol Initializable {

init ()

}

class A : Initializable {

var content:String

required init () {

content = "TestContent"

}

}

func createInstance(typeThing:T.Type) -> T where T:Initializable {

return typeThing.init()

}

let a = createInstance(typeThing: A. self )

type(of: a)

I think this as explained here: Swift Define Constants And Variables - YouTube

Let me know if this is what you were looking for