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?
ArrayType.Element.type
how do I get the element type of the first element of a tuple? I don't see why the latter needs more motivation and is an XY problem when the former clearly has a solution. – Girish