Dictionary Fields and Functions

  let length: Int

The number of entries in the dictionary.

    // Declare a dictionary mapping strings to integers.
    let numbers = {"fortyTwo": 42, "twentyThree": 23}

    // Find the number of entries of the dictionary.
    let length = numbers.length

    // `length` is `2`
  fun insert(key: K, _ value: V): V?

Inserts the given value of type V into the dictionary under the given key of type K.

Returns the previous value as an optional if the dictionary contained the key, otherwise nil.

    // Declare a dictionary mapping strings to integers.
    let numbers = {"twentyThree": 23}

    // Insert the key `"fortyTwo"` with the value `42` into the dictionary.
    // The key did not previously exist in the dictionary,
    // so the result is `nil`
    //
    let old = numbers.insert(key: "fortyTwo", 42)

    // `old` is `nil`
    // `numbers` is `{"twentyThree": 23, "fortyTwo": 42}`
  fun remove(key: K): V?

Removes the value for the given key of type K from the dictionary.

Returns the value of type V as an optional if the dictionary contained the key, otherwise nil.

    // Declare a dictionary mapping strings to integers.
    let numbers = {"fortyTwo": 42, "twentyThree": 23}

    // Remove the key `"fortyTwo"` from the dictionary.
    // The key exists in the dictionary,
    // so the value associated with the key is returned.
    //
    let fortyTwo = numbers.remove(key: "fortyTwo")

    // `fortyTwo` is `42`
    // `numbers` is `{"twentyThree": 23}`

    // Remove the key `"oneHundred"` from the dictionary.
    // The key does not exist in the dictionary, so `nil` is returned.
    //
    let oneHundred = numbers.remove(key: "oneHundred")

    // `oneHundred` is `nil`
    // `numbers` is `{"twentyThree": 23}`
  let keys: [K]

Returns an array of the keys of type K in the dictionary. This does not modify the dictionary, just returns a copy of the keys as an array. If the dictionary is empty, this returns an empty array.

    // Declare a dictionary mapping strings to integers.
    let numbers = {"fortyTwo": 42, "twentyThree": 23}

    // Find the keys of the dictionary.
    let keys = numbers.keys

    // `keys` has type `[String]` and is `["fortyTwo","twentyThree"]`
  let values: [V]

Returns an array of the values of type V in the dictionary. This does not modify the dictionary, just returns a copy of the values as an array. If the dictionary is empty, this returns an empty array.

This field is not available if V is a resource type.

    // Declare a dictionary mapping strings to integers.
    let numbers = {"fortyTwo": 42, "twentyThree": 23}

    // Find the values of the dictionary.
    let values = numbers.values

    // `values` has type [Int] and is `[42, 23]`

Last updated