Reputation: 5238
Is it possible to pass a typealias
as a function parameter in Swift?
I want to do something like:
func doSomethingWithType(type: typealias)
Upvotes: 0
Views: 3637
Reputation: 72750
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)
Upvotes: 4
Reputation: 71854
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) {
}
Upvotes: 1