Swift Tuple index using a variable as the index? Anyone know if it is possible to use a variable as the index for a Swift tuple index. I wish to select and item from a tuple usi
If you've reached a point where you need to access tuple members as if "indexed", you should probably look over your data structure to see if a tuple is really the right choice for you in this case. As MartinR mentions in a comment, perhaps an array would be a more appropriate choice, or, as mentioned by simpleBob, a dictionary.
You can make use of runtime introspection to access the children of a mirror representation of the tuple, and choose a child value given a supplied index.
E.g., for 5-tuples where all elements are of same type:
func getMemberOfFiveTuple(tuple: (T, T, T, T, T), atIndex: Int) -> T? {
let children = Mirror(reflecting: tup).children
guard case let idx = IntMax(atIndex)
where idx < children.count else { return nil }
return children[children.startIndex.advancedBy(idx)].value as? T
}
let tup = (10, 11, 12, 13, 14)
let idx = 3
if let member = getMemberOfFiveTuple(tup, atIndex: idx) {
print(member)
} // 13
Note that the type of child.value is Any, hence we need to perform an attempted type conversion back to the element type of the tuple. In case your tuple contains different-type members, the return type cannot be known at compile time, and you'd probably have to keep using type Any for the returned element.