Array Fields and Functions

Arrays have multiple built-in fields and functions that can be used to get information about and manipulate the contents of the array.

The field length, and the functions concat, and contains are available for both variable-sized and fixed-sized or variable-sized arrays.

  let length: Int

The number of elements in the array.

    // Declare an array of integers.
    let numbers = [42, 23, 31, 12]

    // Find the number of elements of the array.
    let length = numbers.length

    // `length` is `4`
  fun concat(_ array: T): T

Concatenates the parameter array to the end of the array the function is called on, but does not modify that array.

Both arrays must be the same type T.

This function creates a new array whose length is the sum of the length of the array the function is called on and the length of the array given as the parameter.

    // Declare two arrays of integers.
    let numbers = [42, 23, 31, 12]
    let moreNumbers = [11, 27]

    // Concatenate the array `moreNumbers` to the array `numbers`
    // and declare a new variable for the result.
    //
    let allNumbers = numbers.concat(moreNumbers)

    // `allNumbers` is `[42, 23, 31, 12, 11, 27]`
    // `numbers` is still `[42, 23, 31, 12]`
    // `moreNumbers` is still `[11, 27]`
  fun contains(_ element: T): Bool

Returns true if the given element of type T is in the array.

    // Declare an array of integers.
    let numbers = [42, 23, 31, 12]

    // Check if the array contains 11.
    let containsEleven = numbers.contains(11)
    // `containsEleven` is `false`

    // Check if the array contains 12.
    let containsTwelve = numbers.contains(12)
    // `containsTwelve` is `true`

    // Invalid: Check if the array contains the string "Kitty".
    // This results in a type error, as the array only contains integers.
    //
    let containsKitty = numbers.contains("Kitty")

Last updated