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 using a random number. I have the random number as a variable but cannot see how to use that as the index for a tuple. I have searched various places already
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<T>(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.
So, what people here are saying - don't use a tuple if you don't actually need one - is correct. However, there is one caveat.
In my experience, using a Swift Array with a static size in performance critical code actually slows down your code by quite a bit. Take a look:
let clz_lookup = [4, 3, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]
func clz(x : UInt32) -> Int {
guard x != 0 else { return 32 }
var x = x
var n = 0
if (x & 0xFFFF0000) == 0 { n = 16; x <<= 16 } else { n = 0 }
if (x & 0xFF000000) == 0 { n += 8; x <<= 8 }
if (x & 0xF0000000) == 0 { n += 4; x <<= 4 }
return n + clz_lookup[Int(x >> (32 - 4))]
}
This is a fairly straight forward piece of code that uses a cached lookup table at the end. However, if we profile this using instruments we'll see that the lookup is actually much slower than the if statements it replaces! My guess is the reason for that is probably bounds checking or something similar, plus that there is an additional pointer indirection in the implementation.
In any case, that's not good, and since the above is a function that is potentially being called a lot we want to optimise it. A simple technique for that is creating a Tuple instead of an Array, and then simply using withUnsafeMutablePointer
to get a pointer directly into the Tuple (which is laid out as a contiguous, static array in memory - exactly what we want in this case!):
var clz_table = (4, 3, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0)
let clz_lookup = withUnsafeMutablePointer(to: &clz_table) { $0.withMemoryRebound(to: Int.self, capacity: 15) { $0 } }
This can be used exactly like a regular C-style array in that you can index into it and even change the values at particular indices, but there is no way to grow this array. This method of indexing should be much faster than the other solutions that are mentioning reflection, but is potentially unsafe if used wrong.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With