i have a lot of stats counters that store the values inline in a homogenous tuple:
typealias Peers =
(
friends:[Peer],
followers:[Peer],
requested:[Peer],
blocked:[Peer]
)
var count:Int
{
self.friends.count
+ self.followers.count
+ self.requested.count
+ self.blocked.count
}
this is naturally quite error-prone, and i am interested in using parameter packs to simplify the count logic. but i couldn’t deduce how to actually iterate the Peers tuple in the absence of SE-0408, which is nightly-only.
is there a better way to reduce a tuple in swift 5.9?
This implementation will work!
func sumOfCountInTuple<each T: Collection>(_ target: (repeat each T)) -> Int {
var count = 0
func call(with peers: some Collection) {
count += peers.count
}
repeat call(with: each target)
return count
}
print(sumOfCountInTuple(([1,2,3], [4,5], [6,7]))) // 7
Sadly, currently, it is not possible to limit T.Element == Peer though. It produces error: same-element requirements are not yet supported error.
4 Likes
dmt
(Dima Galimzianov)
3
It also seems to be possible to repeat increment directly:
var sum = 0
repeat sum += (each t).count
return sum
What I can't get working is to call this function with a tuple with labels. It produces error: Cannot convert value of type '(a: [Int], b: [String])' to expected argument type '(repeat each T)' or just crashes.
4 Likes