Is it possible to pass a typealias
as a function parameter in Swift?
I want to do something like:
func doSomethingWithType(type: typealias)
How can I pass a typealias as a function parameter in Swift?
3.5k views Asked by sf89 At
2
There are 2 answers
0
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) {
}
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:
You can invoke it by passing a type - for instance:
which will print
If you define a typealias for
String
, the output won't change though: