How can I pass a typealias as a function parameter in Swift?

3.5k views Asked by At

Is it possible to pass a typealias as a function parameter in Swift? I want to do something like: func doSomethingWithType(type: typealias)

2

There are 2 answers

1
Antonio On BEST ANSWER

A type alias is just a synonym for an existing type - it doesn't create a new type, it just create a new name.

That said, if you want to pass a type to a function, you can make it generic, and define it as follows:

func doSomething<T>(type: T.Type) {
    println(type)
}

You can invoke it by passing a type - for instance:

doSomething(String.self)

which will print

"Swift.String"

If you define a typealias for String, the output won't change though:

typealias MyString = String
doSomething(MyString.self)
0
Dharmesh Kheni On

From Apple Document:

A type alias declaration introduces a named alias of an existing type into your program. Type alias declarations are declared using the keyword typealias and have the following form:

typealias name = existing type

After a type alias is declared, the aliased name can be used instead of the existing type everywhere in your program. The existing type can be a named type or a compound type. Type aliases do not create new types; they simply allow a name to refer to an existing type.

So you can use it like this:

typealias yourType = String

func doSomethingWithType(type: yourType) {

}