Last active
May 28, 2025 12:08
-
-
Save ole/95528be9250a13d145939e5a1f963c2d to your computer and use it in GitHub Desktop.
Getting the element count of a tuple in Swift by using variadic generics.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Overload for tuple values. | |
func tupleLength<each T>(_ tuple: (repeat each T)) -> Int { | |
var count = 0 | |
for _ in repeat (each tuple) { | |
count += 1 | |
} | |
return count | |
} | |
tupleLength(()) // → 0 | |
tupleLength(("A")) // → 1 | |
tupleLength((1, 2, 3)) // → 3 | |
tupleLength((1, "A", Void(), false)) // → 4 | |
// Overload for tuple types. | |
func tupleLength<each T>(_: (repeat each T).Type) -> Int { | |
var count = 0 | |
for _ in repeat (each T).self { | |
count += 1 | |
} | |
return count | |
} | |
tupleLength(Void.self) // → 0 | |
tupleLength((Int).self) // → 1 | |
tupleLength((String, String, String).self) // → 3 | |
tupleLength((Int, String, Void, Bool).self) // → 4 | |
let tupleType = (Int, String, Void, Bool).self | |
tupleLength(tupleType) // → 4 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment