Cadence Data Strucuture: Array Deep Dive

Arrays

Arrays are mutable, ordered collections of values. Arrays may contain a value multiple times. Array literals start with an opening square bracket [ and end with a closing square bracket ].

1. Types

Arrays either have a fixed size or are variably sized, i.e., elements can be added and removed.

Fixed-size array types have the form [T; N], where T is the element type, and N is the size of the array. N has to be statically known, meaning that it needs to be an integer literal. For example, a fixed-size array of 3 Int8 elements has the type [Int8; 3].

Variable-size array types have the form [T], where T is the element type. For example, the type [Int16] specifies a variable-size array of elements that have type Int16.

let array: [Int8; 2] = [1, 2] //always contain 2 elements

var variableLengthArray: [Int] = [] // variable length array

let arrays: [[Int16; 3]; 2] = [

[1, 2, 3],

[4, 5, 6]

]

2. Indexing

To get the element of an array at a specific index, the indexing syntax can be used: The array is followed by an opening square bracket [, the indexing value, and ends with a closing square bracket ].

Indexes start at 0 for the first element in the array.

let numbers = [42, 23]

number[0] // results 42

number[1] = 5 // sets to 5

3. 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 numbers = [42, 23, 4, 98]

numbers.length // 4

numbers.conatins(3) // false

numbers.slice(from: 1, upTo: 3) // [23, 4]

numbers.append(3) // numbers is now [42, 23, 4 , 98, 3]