One way to find the range of all values in a Map
in Swift is to use the min()
and max()
functions on the values
property of the Map
. Here's an example:
main.swift284 chars9 lines
In this example, we first create a Map
called myMap
with four key-value pairs. Then, we extract the values of the map using the values
property, which returns a LazyMapCollection
of optional values. To remove the optionals, we use the compactMap
function, which returns a non-optional array of integers. We then use optional binding (if let
) to safely extract the minimum and maximum values from the array. Finally, we create a ClosedRange
with the minimum and maximum values, and print it to the console.
Note that if the map is empty, values.min()
and values.max()
will both return nil
, so we need to handle that case separately.
gistlibby LogSnag