What are the properties “.keys” and “.values” in dictionaries used for?

The properties “.keys” and “.values” in Swift dictionaries are used to access the keys and values of the dictionary as collections.

  • You can use “.keys” to get an array of all the keys in the dictionary
  • or use “.values” to get an array of all the values in the dictionary
var myDict = ["apple": 3, "banana": 5, "orange": 2]
let keys = myDict.keys
let values = myDict.values

print(keys)
print(values)

/* Output: 
["apple", "banana", "orange"]
[3, 5, 2]
*/

Let’s unwrap the code

  • var myDict = [“apple”: 3, “banana”: 5, “orange”: 2]
    • This line creates a dictionary called “myDict” that contains three key-value pairs
    • The keys in the dictionary are “apple”, “banana”, and “orange”, and their corresponding values are 3, 5, and 2, respectively.
  • let keys = myDict.keys
    • This line creates a constant called `keys
    • “myDict.keys” returns an array that contains all the keys in the “myDict” dictionary.
  • let values = myDict.values
    • This line creates a constant called “values”
    • “myDict.values” returns an array that contains all the values in the `myDict` dictionary.
  • print(keys)
    • This line prints the contents of the “keys” constant
    • Since “keys” is an array, this will print all the keys in the “myDict” dictionary.
  • print(values)
    • This line prints the contents of the “values” constant.
    • Since “values” is an array, this will print all the values in the `myDict` dictionary.

Quick notes

  • When using the “.keys” and “.values” properties in Swift dictionaries, it’s important to keep in mind that the order of the elements in the resulting arrays is not guaranteed to be the same as the order in which they were added to the dictionary. This is because dictionaries in Swift are unordered collections.
  • Additionally, both “.keys” and “.values” properties return collections that are immutable as if you wish to modify the keys or values, you will need to create a new dictionary instead.
  • So when using “.keys” and “.values”, you should avoid making any assumptions about ordering and also be aware that the resulting collections cannot be modified directly.

Leave a Reply

Your email address will not be published. Required fields are marked *