I have a function that converts an array into a tuple, if the element count is correct. For example:
let array = [1, 2, 3]
guard let (a, b, c) = array.explode() else {
fatalError("The array must not have had 3 elements")
}
a == 1
b == 2
c == 3
Currently, I have this implemented by a series of functions for the different tuple sizes:
extension Collection {
func explode() -> (Element, Element)?
func explode() -> (Element, Element, Element)?
func explode() -> (Element, Element, Element, Element)?
// etc...
}
I was looking into implementing this using variadic generics instead, but either I haven't found the right incantation, or it's not supported yet. Here's what I'm trying:
// Error: Same-element constraints are not yet implemented
func explode<each T>() -> (repeat each T)
where repeat each T == Element
{
var itr = self.makeIterator()
return (repeat itr.next() as! each T)
}
I can remove the where
clause and write out all the types manually like this:
let (a, b, c): (Int, Int, Int) = [1, 2, 3].explode()!
But that becomes quite unwieldy as the number of elements scales. I already have manual variants implemented for 2–6 elements, so I'm really hoping to get something that can handle large numbers better.
Is there a way to write this right now?