Splitting Dictionary into Keys and Values

I want to separate a dictionary into an array of keys and an array of values, with the only condition that the order of each element in the arrays must agree.

So I would like to know if this is safe:

let dictionary = [4: "4", 5: "5", 8: "8"]
let keys = Array(dictionary.keys)
let values = Array(dictionary.values)

// keys = [5, 4, 8]
// values = ["5", "4", "8"]

Since Keys and Values seem to be backed by original Dictionary (or more precisely, its Variant) and so they share the same Collection.indices.
Though I'm unsure how future-proof this is.

If this is not safe, I would like to ask for a swift-y way to do it.

Yes, the base dictionary, its keys view, and its values view all iterate over the same indices in the same order, so they produce matching elements.

Terms of Service

Privacy Policy

Cookie Policy