Last active
November 22, 2024 19:57
-
-
Save ole/95528be9250a13d145939e5a1f963c2d to your computer and use it in GitHub Desktop.
Getting the element count of a tuple in Swift
This file contains 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