let dict = [1:"One", 2:"Two", 3:"Three"]
let values = dict.values
print(values.dynamicType)
prints:
LazyMapCollection<Dictionary<Int, String>, String>
There are two things I don't understand here. Wouldn't it be a bit more simple if values
returned an Array
? Also, what is LazyMapCollection
? I looked into Apple's reference but it provides literally no information (or nothing I am able to make sense of).
You can iterate over this object, because it is CollectionType
:
for v in values {
print(v)
}
prints:
Two
Three
One
But for some reason Apple didn't use Array
type.
A LazyMapCollection is a lazy (only evaluated if necessary) view on a collection. By "view" I mean "window", "frame", "virtual subset", this kind of concept.
To get the actual values from it, just use the Array initializer:
let values = dict.values
let result = Array(values)
You have here a serious speed optimisation. Creating an array is expensive. Instead you get an instance of some strange class that behaves in every way like an array. However, it doesn't have its data stored in a real array, instead it access the data from a dictionary.
Say you have a dictionary with 10,000 string values. You don't want iOS to copy all the 10,000 string values when you call dict.values, do you? That's what this class is there for, to prevent copying 10,000 strings. A real array would force copying.
And anyway, with your username you are asking for things like this, and Apple provides many examples. That's how they make iOS fast.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With