How to create an (efficient) collection view over a Dictionary?

i have a dictionary of the form

let dictionary:[X: Y]

and i want to create a zero-cost view abstraction that wraps this dictionary, where the view is a collection of Z, and where Z is just an aggregate of X and Y:

struct Z 
    init(x:X, y:Y)

my first idea was to use Dictionary.Indices and wrap Dictionary’s own Collection conformance:

extension ZCollectionView 
    subscript(index:Dictionary<X, Y>.Index) -> Z

but then i realized this would not be a zero-cost abstraction, because Dictionary.subscript(_:) checks a canary stored in Dictionary.Index.

i assume the standard library has a special optimization pass that lets us iterate through dictionary items in a for loop without overhead. but my ZCollectionView would probably not benefit from such an optimization.

Your wrapped type is essentially { Z(x: $0.0, y: $0.1) }. You could implement it as literally that, or you could return an Iterator that wraps Dictionary’s Iterator to do the same instead of relying on IndexingIterator. I don’t think there’s any additional magic today.