Reputation: 103
I have been exploring different abstractions in Swift, and I found myself stumped on how to determine the type of a tuple's element from its own type. I know the compiler and Xcode are quick to provide such information to me, the coder, and I know how to use type(of:)
on the elements of a tuple variable or constant, but I cannot seem to figure out how to do it from code using only the tuple type.
Here is my question using incomplete code:
// Somewhere else in the code...
typealias NamedTuple = (/*someunknowntype*/, /*someotherunknowntype*/)
// Later in the code...
let tupleType = NamedTuple.self // repetitive, I know... but I know how to get its own type
let tupleElement0Type = // <-- How do I get this from the NamedTuple alias?
I cannot seem to discover any documentation that mentions a way to access a tuple's elements from its type name or literal format, although the latter would be silly.
I already know how to work around such issues using generic solutions. I am just looking for something straight forward, like with .self
on a type name or alias.
I can already get the element types of arrays (ArrayType.Element.type
) and dictionaries (Dictionary.Key.self
and Dictionary.Value.self
), but those are obviously through their typealias
properties.
Does anyone know how to type the elements of a type directly from its name or alias? Or, at a minimum, from collections types other than an Array or a Dictionary?
Upvotes: 6
Views: 472
Reputation: 32853
For tuples without labels, this can be achieved via parameter packs:
func tupleTypes<each T>(_: (repeat (each T)).Type) -> (repeat (each T).Type) {
((repeat (each T).self))
}
typealias MyTuple = (Int, String, [Double])
print(tupleTypes(MyTuple.self))
// (Swift.Int, Swift.String, Swift.Array<Swift.Double>)
let types = tupleTypes(MyTuple.self)
print(types.0)
// Int
Upvotes: 2