Why is the “values” property in the dictionary not a simple array, but is it something weird instead?

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 that I don’t understand here. Wouldn't it be a little easier if values returned Array ? Also, what is a LazyMapCollection ? I looked at the Apple link , but it does not provide literally any information (or can’t understand anything). 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 did not use the Array type.

+5
source share
3 answers

A LazyMapCollection is a lazy (only evaluated when necessary) view of a collection. By “view” I mean “window”, “frame”, “virtual subset”, such a concept.

To get the actual values ​​from it, just use an array initializer:

 let values = dict.values let result = Array(values) 
+4
source

You have serious speed optimization here. Creating an array is expensive. Instead, you get an instance of some weird class that behaves like an array. However, it does not have its data stored in a real array; instead, it gets access to data from the dictionary.

Say you have a dictionary with 10,000 string values. You don't want iOS to copy all 10,000 string values ​​when you call dict.values, right? This is what this class is for, to prevent copying of 10,000 lines. A real array will force copy.

In general, with your username you ask for such things, and Apple provides many examples. This is how they quickly make iOS.

+3
source

Both arrays and dictionaries are value types (structs). This means that after the array request, the values ​​must be copied. If Dictionary.values returned an array, this can be an expensive performance operation - and usually not needed, because most of the time you only want to iterate over the values.

Thus, using a special (lazy) type of collection is basically a way to prevent copying when copying is not required. If you need a copy, you must ask for it explicitly.

+2
source

Source: https://habr.com/ru/post/1236417/


All Articles