# Values and Types

Values are objects, like for example booleans, integers, or arrays. Values are typed.

## Booleans

The two boolean values `true` and `false` have the type `Bool`.

## Numeric Literals

Numbers can be written in various bases. Numbers are assumed to be decimal by default. Non-decimal literals have a specific prefix.

Numeral systemPrefixCharacters
DecimalNoneone or more numbers (`0` to `9`)
Binary`0b`one or more zeros or ones (`0` or `1`)
Octal`0o`one or more numbers in the range `0` to `7`
Hexadecimal`0x`one or more numbers, or characters `a` to `f`, lowercase or uppercase
```1// A decimal number2//31234567890  // is `1234567890`4
5// A binary number6//70b101010  // is `42`8
9// An octal number10//110o12345670  // is `2739128`12
13// A hexadecimal number14//150x1234567890ABCabc  // is `1311768467294898876`16
17// Invalid: unsupported prefix 0z18//190z020
21// A decimal number with leading zeros. Not an octal number!2200123 // is `123`23
24// A binary number with several trailing zeros.250b001000  // is `8````

Decimal numbers may contain underscores (`_`) to logically separate components.

```1let largeNumber = 1_000_0002
3// Invalid: Value is not a number literal, but a variable.4let notNumber = _123```

Underscores are allowed for all numeral systems.

`1let binaryNumber = 0b10_11_01`

## Integers

Integers are numbers without a fractional part. They are either signed (positive, zero, or negative) or unsigned (positive or zero).

Signed integer types which check for overflow and underflow have an `Int` prefix and can represent values in the following ranges:

• `Int8`: -2^7 through 2^7 − 1 (-128 through 127)
• `Int16`: -2^15 through 2^15 − 1 (-32768 through 32767)
• `Int32`: -2^31 through 2^31 − 1 (-2147483648 through 2147483647)
• `Int64`: -2^63 through 2^63 − 1 (-9223372036854775808 through 9223372036854775807)
• `Int128`: -2^127 through 2^127 − 1
• `Int256`: -2^255 through 2^255 − 1

Unsigned integer types which check for overflow and underflow have a `UInt` prefix and can represent values in the following ranges:

• `UInt8`: 0 through 2^8 − 1 (255)
• `UInt16`: 0 through 2^16 − 1 (65535)
• `UInt32`: 0 through 2^32 − 1 (4294967295)
• `UInt64`: 0 through 2^64 − 1 (18446744073709551615)
• `UInt128`: 0 through 2^128 − 1
• `UInt256`: 0 through 2^256 − 1

Unsigned integer types which do not check for overflow and underflow, i.e. wrap around, have the `Word` prefix and can represent values in the following ranges:

• `Word8`: 0 through 2^8 − 1 (255)
• `Word16`: 0 through 2^16 − 1 (65535)
• `Word32`: 0 through 2^32 − 1 (4294967295)
• `Word64`: 0 through 2^64 − 1 (18446744073709551615)

The types are independent types, i.e. not subtypes of each other.

See the section about arithmetic operators for further information about the behavior of the different integer types.

`1// Declare a constant that has type `UInt8` and the value 10.2let smallNumber: UInt8 = 10`
`1// Invalid: negative literal cannot be used as an unsigned integer2//3let invalidNumber: UInt8 = -10`

In addition, the arbitrary precision integer type `Int` is provided.

`1let veryLargeNumber: Int = 10000000000000000000000000000000`

Integer literals are inferred to have type `Int`, or if the literal occurs in a position that expects an explicit type, e.g. in a variable declaration with an explicit type annotation.

```1let someNumber = 1232
3// `someNumber` has type `Int````

Negative integers are encoded in two's complement representation.

Integer types are not converted automatically. Types must be explicitly converted, which can be done by calling the constructor of the type with the integer type.

```1let x: Int8 = 12let y: Int16 = 23
4// Invalid: the types of the operands, `Int8` and `Int16` are incompatible.5let z = x + y6
7// Explicitly convert `x` from `Int8` to `Int16`.8let a = Int16(x) + y9
10// `a` has type `Int16`11
12// Invalid: The integer literal is expected to be of type `Int8`,13// but the large integer literal does not fit in the range of `Int8`.14//15let b = x + 1000000000000000000000000```

### Integer Functions

Integers have multiple built-in functions you can use.

• `cadence•fun toString(): String`

Returns the string representation of the integer.

```1let answer = 422
3answer.toString()  // is "42"```
• `cadence•fun toBigEndianBytes(): [UInt8]`

Returns the byte array representation (`[UInt8]`) in big-endian order of the integer.

```1let largeNumber = 12345678902
3largeNumber.toBigEndianBytes()  // is `[73, 150, 2, 210]````

## Fixed-Point Numbers

🚧 Status: Currently only the 64-bit wide `Fix64` and `UFix64` types are available. More fixed-point number types will be added in a future release.

Fixed-point numbers are useful for representing fractional values. They have a fixed number of digits after decimal point.

They are essentially integers which are scaled by a factor. For example, the value 1.23 can be represented as 1230 with a scaling factor of 1/1000. The scaling factor is the same for all values of the same type and stays the same during calculations.

Fixed-point numbers in Cadence have a scaling factor with a power of 10, instead of a power of 2, i.e. they are decimal, not binary.

Signed fixed-point number types have the prefix `Fix`, have the following factors, and can represent values in the following ranges:

• `Fix64`: Factor 1/100,000,000; -92233720368.54775808 through 92233720368.54775807

Unsigned fixed-point number types have the prefix `UFix`, have the following factors, and can represent values in the following ranges:

• `UFix64`: Factor 1/100,000,000; 0.0 through 184467440737.09551615

### Fixed-Point Number Functions

Fixed-Point numbers have multiple built-in functions you can use.

• `cadence•fun toString(): String`

Returns the string representation of the fixed-point number.

```1let fix = 1.232
3fix.toString()  // is "1.23000000"```
• `cadence•fun toBigEndianBytes(): [UInt8]`

Returns the byte array representation (`[UInt8]`) in big-endian order of the fixed-point number.

```1let fix = 1.232
3fix.toBigEndianBytes()  // is `[0, 0, 0, 0, 7, 84, 212, 192]````

## Minimum and maximum values

The minimum and maximum values for all integer and fixed-point number types are available through the fields `min` and `max`.

For example:

`1let max = UInt8.max2// `max` is 255, the maximum value of the type `UInt8``
`1let max = UFix64.max2// `max` is 184467440737.09551615, the maximum value of the type `UFix64``

## Saturation Arithmetic

Integers and fixed-point numbers support saturation arithmetic: Arithmetic operations, such as addition or multiplications, are saturating at the numeric bounds instead of overflowing.

If the result of an operation is greater than the maximum value of the operands' type, the maximum is returned. If the result is lower than the minimum of the operands' type, the minimum is returned.

Saturating addition, subtraction, multiplication, and division are provided as functions with the prefix `saturating`:

• `Int8`, `Int16`, `Int32`, `Int64`, `Int128`, `Int256`, `Fix64`:

• `saturatingAdd`
• `saturatingSubtract`
• `saturatingMultiply`
• `saturatingDivide`
• `Int`:

• none
• `UInt8`, `UInt16`, `UInt32`, `UInt64`, `UInt128`, `UInt256`, `UFix64`:

• `saturatingAdd`
• `saturatingSubtract`
• `saturatingMultiply`
• `UInt`:

• `saturatingSubtract`
`1let a: UInt8 = 2002let b: UInt8 = 1003let result = a.saturatingAdd(b)4// `result` is 255, the maximum value of the type `UInt8``

## Floating-Point Numbers

There is no support for floating point numbers.

Smart Contracts are not intended to work with values with error margins and therefore floating point arithmetic is not appropriate here.

Instead, consider using fixed point numbers.

The type `Address` represents an address. Addresses are unsigned integers with a size of 64 bits (8 bytes). Hexadecimal integer literals can be used to create address values.

```1// Declare a constant that has type `Address`.2//3let someAddress: Address = 0x436164656E6365214
5// Invalid: Initial value is not compatible with type `Address`,6// it is not a number.7//8let notAnAddress: Address = ""9
10// Invalid: Initial value is not compatible with type `Address`.11// The integer literal is valid, however, it is larger than 64 bits.12//13let alsoNotAnAddress: Address = 0x436164656E63652146757265766572```

Integer literals are not inferred to be an address.

```1// Declare a number. Even though it happens to be a valid address,2// it is not inferred as it.3//4let aNumber = 0x436164656E6365215
6// `aNumber` has type `Int````

Addresses have multiple built-in functions you can use.

• `cadence•fun toString(): String`

Returns the string representation of the address. The result has a `0x` prefix and is zero-padded.

```1let someAddress: Address = 0x436164656E6365212someAddress.toString()   // is "0x436164656E636521"3
• `cadence•fun toBytes(): [UInt8]`

Returns the byte array representation (`[UInt8]`) of the address.

```1let someAddress: Address = 0x436164656E6365212
3someAddress.toBytes()  // is `[67, 97, 100, 101, 110, 99, 101, 33]````

## AnyStruct and AnyResource

`AnyStruct` is the top type of all non-resource types, i.e., all non-resource types are a subtype of it.

`AnyResource` is the top type of all resource types.

```1// Declare a variable that has the type `AnyStruct`.2// Any non-resource typed value can be assigned to it, for example an integer,3// but not resource-typed values.4//5var someStruct: AnyStruct = 16
7// Assign a value with a different non-resource type, `Bool`.8someStruct = true9
10// Declare a structure named `TestStruct`, create an instance of it,11// and assign it to the `AnyStruct`-typed variable12//13struct TestStruct {}14
15let testStruct = TestStruct()16
17someStruct = testStruct18
19// Declare a resource named `TestResource`20
21resource TestResource {}22
23// Declare a variable that has the type `AnyResource`.24// Any resource-typed value can be assigned to it,25// but not non-resource typed values.26//27var someResource: @AnyResource <- create TestResource()28
29// Invalid: Resource-typed values can not be assigned30// to `AnyStruct`-typed variables31//32someStruct <- create TestResource()33
34// Invalid: Non-resource typed values can not be assigned35// to `AnyResource`-typed variables36//37someResource = 1```

However, using `AnyStruct` and `AnyResource` does not opt-out of type checking. It is invalid to access fields and call functions on these types, as they have no fields and functions.

```1// Declare a variable that has the type `AnyStruct`.2// The initial value is an integer,3// but the variable still has the explicit type `AnyStruct`.4//5let a: AnyStruct = 16
7// Invalid: Operator cannot be used for an `AnyStruct` value (`a`, left-hand side)8// and an `Int` value (`2`, right-hand side).9//10a + 2```

`AnyStruct` and `AnyResource` may be used like other types, for example, they may be the element type of arrays or be the element type of an optional type.

```1// Declare a variable that has the type `[AnyStruct]`,2// i.e. an array of elements of any non-resource type.3//4let anyValues: [AnyStruct] = [1, "2", true]5
6// Declare a variable that has the type `AnyStruct?`,7// i.e. an optional type of any non-resource type.8//9var maybeSomething: AnyStruct? = 4210
11maybeSomething = "twenty-four"12
13maybeSomething = nil```

`AnyStruct` is also the super-type of all non-resource optional types, and `AnyResource` is the super-type of all resource optional types.

`1let maybeInt: Int? = 12let anything: AnyStruct = maybeInt`

Conditional downcasting allows coercing a value which has the type `AnyStruct` or `AnyResource` back to its original type.

## Optionals

Optionals are values which can represent the absence of a value. Optionals have two cases: either there is a value, or there is nothing.

An optional type is declared using the `?` suffix for another type. For example, `Int` is a non-optional integer, and `Int?` is an optional integer, i.e. either nothing, or an integer.

The value representing nothing is `nil`.

```1// Declare a constant which has an optional integer type,2// with nil as its initial value.3//4let a: Int? = nil5
6// Declare a constant which has an optional integer type,7// with 42 as its initial value.8//9let b: Int? = 4210
11// Invalid: `b` has type `Int?`, which does not support arithmetic.12b + 2313
14// Invalid: Declare a constant with a non-optional integer type `Int`,15// but the initial value is `nil`, which in this context has type `Int?`.16//17let x: Int = nil```

Optionals can be created for any value, not just for literals.

```1// Declare a constant which has a non-optional integer type,2// with 1 as its initial value.3//4let x = 15
6// Declare a constant which has an optional integer type.7// An optional with the value of `x` is created.8//9let y: Int? = x10
11// Declare a variable which has an optional any type, i.e. the variable12// may be `nil`, or any other value.13// An optional with the value of `x` is created.14//15var z: AnyStruct? = x```

A non-optional type is a subtype of its optional type.

```1var a: Int? = nil2let b = 23a = b4
5// `a` is `2````

Optional types may be contained in other types, for example arrays or even optionals.

```1// Declare a constant which has an array type of optional integers.2let xs: [Int?] = [1, nil, 2, nil]3
4// Declare a constant which has a double optional type.5//6let doubleOptional: Int?? = nil```

See the optional operators section for information on how to work with optionals.

## Never

`Never` is the bottom type, i.e., it is a subtype of all types. There is no value that has type `Never`. `Never` can be used as the return type for functions that never return normally. For example, it is the return type of the function `panic`.

```1// Declare a function named `crashAndBurn` which will never return,2// because it calls the function named `panic`, which never returns.3//4fun crashAndBurn(): Never {5    panic("An unrecoverable error occurred")6}7
8// Invalid: Declare a constant with a `Never` type, but the initial value is an integer.9//10let x: Never = 111
12// Invalid: Declare a function which returns an invalid return value `nil`,13// which is not a value of type `Never`.14//15fun returnNever(): Never {16    return nil17}```

## Strings and Characters

Strings are collections of characters. Strings have the type `String`, and characters have the type `Character`. Strings can be used to work with text in a Unicode-compliant way. Strings are immutable.

String and character literals are enclosed in double quotation marks (`"`).

`1let someString = "Hello, world!"`

String literals may contain escape sequences. An escape sequence starts with a backslash (`\`):

• `\0`: Null character
• `\\`: Backslash
• `\t`: Horizontal tab
• `\n`: Line feed
• `\r`: Carriage return
• `\"`: Double quotation mark
• `\'`: Single quotation mark
• `\u`: A Unicode scalar value, written as `\u{x}`, where `x` is a 1–8 digit hexadecimal number which needs to be a valid Unicode scalar value, i.e., in the range 0 to 0xD7FF and 0xE000 to 0x10FFFF inclusive
`1// Declare a constant which contains two lines of text2// (separated by the line feed character `\n`), and ends3// with a thumbs up emoji, which has code point U+1F44D (0x1F44D).4//5let thumbsUpText =6    "This is the first line.\nThis is the second line with an emoji: \u{1F44D}"`

The type `Character` represents a single, human-readable character. Characters are extended grapheme clusters, which consist of one or more Unicode scalars.

For example, the single character `ü` can be represented in several ways in Unicode. First, it can be represented by a single Unicode scalar value `ü` ("LATIN SMALL LETTER U WITH DIAERESIS", code point U+00FC). Second, the same single character can be represented by two Unicode scalar values: `u` ("LATIN SMALL LETTER U", code point U+0075), and "COMBINING DIAERESIS" (code point U+0308). The combining Unicode scalar value is applied to the scalar before it, which turns a `u` into a `ü`.

Still, both variants represent the same human-readable character `ü`.

`1let singleScalar: Character = "\u{FC}"2// `singleScalar` is `ü`3let twoScalars: Character = "\u{75}\u{308}"4// `twoScalars` is `ü``

Another example where multiple Unicode scalar values are rendered as a single, human-readable character is a flag emoji. These emojis consist of two "REGIONAL INDICATOR SYMBOL LETTER" Unicode scalar values.

`1// Declare a constant for a string with a single character, the emoji2// for the Canadian flag, which consists of two Unicode scalar values:3// - REGIONAL INDICATOR SYMBOL LETTER C (U+1F1E8)4// - REGIONAL INDICATOR SYMBOL LETTER A (U+1F1E6)5//6let canadianFlag: Character = "\u{1F1E8}\u{1F1E6}"7// `canadianFlag` is `🇨🇦``

### String Fields and Functions

Strings have multiple built-in functions you can use:

• `cadence•let length: Int`

Returns the number of characters in the string as an integer.

```1let example = "hello"2
3// Find the number of elements of the string.4let length = example.length5// `length` is `5````
• `cadence•let utf8: [UInt8]`

The byte array of the UTF-8 encoding

`1let flowers = "Flowers \u{1F490}"2let bytes = flowers.utf83// `bytes` is `[70, 108, 111, 119, 101, 114, 115, 32, 240, 159, 146, 144]``
• `cadence•fun concat(_ other: String): String`

Concatenates the string `other` to the end of the original string, but does not modify the original string. This function creates a new string whose length is the sum of the lengths of the string the function is called on and the string given as a parameter.

```1let example = "hello"2let new = "world"3
4// Concatenate the new string onto the example string and return the new string.5let helloWorld = example.concat(new)6// `helloWorld` is now `"helloworld"````
• `cadence•fun slice(from: Int, upTo: Int): String`

Returns a string slice of the characters in the given string from start index `from` up to, but not including, the end index `upTo`. This function creates a new string whose length is `upTo - from`. It does not modify the original string. If either of the parameters are out of the bounds of the string, or the indices are invalid (`from > upTo`), then the function will fail.

```1let example = "helloworld"2
3// Create a new slice of part of the original string.4let slice = example.slice(from: 3, upTo: 6)5// `slice` is now `"low"`6
7// Run-time error: Out of bounds index, the program aborts.8let outOfBounds = example.slice(from: 2, upTo: 10)9
10// Run-time error: Invalid indices, the program aborts.11let invalidIndices = example.slice(from: 2, upTo: 1)```
• `cadence•fun decodeHex(): [UInt8]`

Returns an array containing the bytes represented by the given hexadecimal string.

The given string must only contain hexadecimal characters and must have an even length. If the string is malformed, the program aborts

```1let example = "436164656e636521"2
3example.decodeHex()  // is `[67, 97, 100, 101, 110, 99, 101, 33]````
• `cadence•fun toLower(): String` Returns a string where all upper case letters are replaced with lowercase characters

```1let example = "Flowers"2
3example.toLower()  // is `flowers````

The `String` type also provides the following functions:

• `cadence•fun String.encodeHex(_ data: [UInt8]): String`

Returns a hexadecimal string for the given byte array

```1let data = [1 as UInt8, 2, 3, 0xCA, 0xDE]2
3String.encodeHex(data)  // is `"010203cade"````

`String`s are also indexable, returning a `Character` value.

`1let str = "abc"2let c = str // is the Character "a"`

### Character Fields and Functions

`Character` values can be converted into `String` values using the `toString` function:

• `cadence•fun toString(): String`

Returns the string representation of the character.

```1let c: Character = "x"2
3c.toString()  // is "x"```

## 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// An empty array2//3[]4
5// An array with integers6//7[1, 2, 3]```

### Array 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`.

All values in an array must have a type which is a subtype of the array's element type (`T`).

It is important to understand that arrays are value types and are only ever copied when used as an initial value for a constant or variable, when assigning to a variable, when used as function argument, or when returned from a function call.

```1let size = 22// Invalid: Array-size must be an integer literal3let numbers: [Int; size] = []4
5// Declare a fixed-sized array of integers6// which always contains exactly two elements.7//8let array: [Int8; 2] = [1, 2]9
10// Declare a fixed-sized array of fixed-sized arrays of integers.11// The inner arrays always contain exactly three elements,12// the outer array always contains two elements.13//14let arrays: [[Int16; 3]; 2] = [15    [1, 2, 3],16    [4, 5, 6]17]18
19// Declare a variable length array of integers20var variableLengthArray: [Int] = []21
22// Mixing values with different types is possible23// by declaring the expected array type24// with the common supertype of all values.25//26let mixedValues: [AnyStruct] = ["some string", 42]```

Array types are covariant in their element types. For example, `[Int]` is a subtype of `[AnyStruct]`. This is safe because arrays are value types and not reference types.

### Array 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.

Accessing an element which is out of bounds results in a fatal error at run-time and aborts the program.

```1// Declare an array of integers.2let numbers = [42, 23]3
4// Get the first number of the array.5//6numbers // is `42`7
8// Get the second number of the array.9//10numbers // is `23`11
12// Run-time error: Index 2 is out of bounds, the program aborts.13//14numbers```
```1// Declare an array of arrays of integers, i.e. the type is `[[Int]]`.2let arrays = [[1, 2], [3, 4]]3
4// Get the first number of the second array.5//6arrays // is `3````

To set an element of an array at a specific index, the indexing syntax can be used as well.

```1// Declare an array of integers.2let numbers = [42, 23]3
4// Change the second number in the array.5//6// NOTE: The declaration `numbers` is constant, which means that7// the *name* is constant, not the *value* – the value, i.e. the array,8// is mutable and can be changed.9//10numbers = 211
12// `numbers` is `[42, 2]````

### 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.

• `cadence•let length: Int`

The number of elements in the array.

```1// Declare an array of integers.2let numbers = [42, 23, 31, 12]3
4// Find the number of elements of the array.5let length = numbers.length6
7// `length` is `4````
• `cadence•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.

```1// Declare two arrays of integers.2let numbers = [42, 23, 31, 12]3let moreNumbers = [11, 27]4
5// Concatenate the array `moreNumbers` to the array `numbers`6// and declare a new variable for the result.7//8let allNumbers = numbers.concat(moreNumbers)9
10// `allNumbers` is `[42, 23, 31, 12, 11, 27]`11// `numbers` is still `[42, 23, 31, 12]`12// `moreNumbers` is still `[11, 27]````
• `cadence•fun contains(_ element: T): Bool`

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

```1// Declare an array of integers.2let numbers = [42, 23, 31, 12]3
4// Check if the array contains 11.5let containsEleven = numbers.contains(11)6// `containsEleven` is `false`7
8// Check if the array contains 12.9let containsTwelve = numbers.contains(12)10// `containsTwelve` is `true`11
12// Invalid: Check if the array contains the string "Kitty".13// This results in a type error, as the array only contains integers.14//15let containsKitty = numbers.contains("Kitty")```
• `cadence•fun firstIndex(of: T): Int?` Returns the index of the first element matching the given object in the array, nil if no match. Available if `T` is not resource-kinded and equatable.

```1// Declare an array of integers.2 let numbers = [42, 23, 31, 12]3
4 // Check if the array contains 315 let index = numbers.firstIndex(of: 31)6 // `index` is 27
8 // Check if the array contains 229 let index = numbers.firstIndex(of: 22)10 // `index` is nil```
• `cadence•fun slice(from: Int, upTo: Int): [T]`

Returns an array slice of the elements in the given array from start index `from` up to, but not including, the end index `upTo`. This function creates a new array whose length is `upTo - from`. It does not modify the original array. If either of the parameters are out of the bounds of the array, or the indices are invalid (`from > upTo`), then the function will fail.

```1let example = [1, 2, 3, 4]2
3// Create a new slice of part of the original array.4let slice = example.slice(from: 1, upTo: 3)5// `slice` is now `[2, 3]`6
7// Run-time error: Out of bounds index, the program aborts.8let outOfBounds = example.slice(from: 2, upTo: 10)9
10// Run-time error: Invalid indices, the program aborts.11let invalidIndices = example.slice(from: 2, upTo: 1)```

#### Variable-size Array Functions

The following functions can only be used on variable-sized arrays. It is invalid to use one of these functions on a fixed-sized array.

• `cadence•fun append(_ element: T): Void`

Adds the new element `element` of type `T` to the end of the array.

The new element must be the same type as all the other elements in the array.

This function mutates the array.

```1// Declare an array of integers.2let numbers = [42, 23, 31, 12]3
4// Add a new element to the array.5numbers.append(20)6// `numbers` is now `[42, 23, 31, 12, 20]`7
8// Invalid: The parameter has the wrong type `String`.9numbers.append("SneakyString")```
• `cadence•fun appendAll(_ array: T): Void`

Adds all the elements from `array` to the end of the array the function is called on.

Both arrays must be the same type `T`.

This function mutates the array.

```1// Declare an array of integers.2let numbers = [42, 23]3
4// Add new elements to the array.5numbers.appendAll([31, 12, 20])6// `numbers` is now `[42, 23, 31, 12, 20]`7
8// Invalid: The parameter has the wrong type `[String]`.9numbers.appendAll(["Sneaky", "String"])```
• `cadence•fun insert(at index: Int, _ element: T): Void`

Inserts the new element `element` of type `T` at the given `index` of the array.

The new element must be of the same type as the other elements in the array.

The `index` must be within the bounds of the array. If the index is outside the bounds, the program aborts.

The existing element at the supplied index is not overwritten.

All the elements after the new inserted element are shifted to the right by one.

This function mutates the array.

```1// Declare an array of integers.2let numbers = [42, 23, 31, 12]3
4// Insert a new element at position 1 of the array.5numbers.insert(at: 1, 20)6// `numbers` is now `[42, 20, 23, 31, 12]`7
8// Run-time error: Out of bounds index, the program aborts.9numbers.insert(at: 12, 39)```
• `cadence•fun remove(at index: Int): T`

Removes the element at the given `index` from the array and returns it.

The `index` must be within the bounds of the array. If the index is outside the bounds, the program aborts.

This function mutates the array.

```1// Declare an array of integers.2let numbers = [42, 23, 31]3
4// Remove element at position 1 of the array.5let twentyThree = numbers.remove(at: 1)6// `numbers` is now `[42, 31]`7// `twentyThree` is `23`8
9// Run-time error: Out of bounds index, the program aborts.10numbers.remove(at: 19)```
• `cadence•fun removeFirst(): T`

Removes the first element from the array and returns it.

The array must not be empty. If the array is empty, the program aborts.

This function mutates the array.

```1// Declare an array of integers.2let numbers = [42, 23]3
4// Remove the first element of the array.5let fortytwo = numbers.removeFirst()6// `numbers` is now ``7// `fortywo` is `42`8
9// Remove the first element of the array.10let twentyThree = numbers.removeFirst()11// `numbers` is now `[]`12// `twentyThree` is `23`13
14// Run-time error: The array is empty, the program aborts.15numbers.removeFirst()```
• `cadence•fun removeLast(): T`

Removes the last element from the array and returns it.

The array must not be empty. If the array is empty, the program aborts.

This function mutates the array.

```1// Declare an array of integers.2let numbers = [42, 23]3
4// Remove the last element of the array.5let twentyThree = numbers.removeLast()6// `numbers` is now ``7// `twentyThree` is `23`8
9// Remove the last element of the array.10let fortyTwo = numbers.removeLast()11// `numbers` is now `[]`12// `fortyTwo` is `42`13
14// Run-time error: The array is empty, the program aborts.15numbers.removeLast()```

## Dictionaries

Dictionaries are mutable, unordered collections of key-value associations. Dictionaries may contain a key only once and may contain a value multiple times.

Dictionary literals start with an opening brace `{` and end with a closing brace `}`. Keys are separated from values by a colon, and key-value associations are separated by commas.

```1// An empty dictionary2//3{}4
5// A dictionary which associates integers with booleans6//7{8    1: true,9    2: false10}```

### Dictionary Types

Dictionary types have the form `{K: V}`, where `K` is the type of the key, and `V` is the type of the value. For example, a dictionary with `Int` keys and `Bool` values has type `{Int: Bool}`.

In a dictionary, all keys must have a type that is a subtype of the dictionary's key type (`K`) and all values must have a type that is a subtype of the dictionary's value type (`V`).

```1// Declare a constant that has type `{Int: Bool}`,2// a dictionary mapping integers to booleans.3//4let booleans = {5    1: true,6    0: false7}8
9// Declare a constant that has type `{Bool: Int}`,10// a dictionary mapping booleans to integers.11//12let integers = {13    true: 1,14    false: 015}16
17// Mixing keys with different types, and mixing values with different types,18// is possible by declaring the expected dictionary type with the common supertype19// of all keys, and the common supertype of all values.20//21let mixedValues: {String: AnyStruct} = {22    "a": 1,23    "b": true24}```

Dictionary types are covariant in their key and value types. For example, `{Int: String}` is a subtype of `{AnyStruct: String}` and also a subtype of `{Int: AnyStruct}`. This is safe because dictionaries are value types and not reference types.

### Dictionary Access

To get the value for a specific key from a dictionary, the access syntax can be used: The dictionary is followed by an opening square bracket `[`, the key, and ends with a closing square bracket `]`.

Accessing a key returns an optional: If the key is found in the dictionary, the value for the given key is returned, and if the key is not found, `nil` is returned.

```1// Declare a constant that has type `{Int: Bool}`,2// a dictionary mapping integers to booleans.3//4let booleans = {5    1: true,6    0: false7}8
9// The result of accessing a key has type `Bool?`.10//11booleans  // is `true`12booleans  // is `false`13booleans  // is `nil`14
15// Invalid: Accessing a key which does not have type `Int`.16//17booleans["1"]```
```1// Declare a constant that has type `{Bool: Int}`,2// a dictionary mapping booleans to integers.3//4let integers = {5    true: 1,6    false: 07}8
9// The result of accessing a key has type `Int?`10//11integers[true] // is `1`12integers[false] // is `0````

To set the value for a key of a dictionary, the access syntax can be used as well.

```1// Declare a constant that has type `{Int: Bool}`,2// a dictionary mapping booleans to integers.3//4let booleans = {5    1: true,6    0: false7}8
9// Assign new values for the keys `1` and `0`.10//11booleans = false12booleans = true13// `booleans` is `{1: false, 0: true}````

### Dictionary Fields and Functions

• `cadence•let length: Int`

The number of entries in the dictionary.

```1// Declare a dictionary mapping strings to integers.2let numbers = {"fortyTwo": 42, "twentyThree": 23}3
4// Find the number of entries of the dictionary.5let length = numbers.length6
7// `length` is `2````
• `cadence•fun insert(key: K, _ value: V): V?`

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

The inserted key must have the same type as the dictionary's key type, and the inserted value must have the same type as the dictionary's value type.

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

Updates the value if the dictionary already contained the key.

This function mutates the dictionary.

```1// Declare a dictionary mapping strings to integers.2let numbers = {"twentyThree": 23}3
4// Insert the key `"fortyTwo"` with the value `42` into the dictionary.5// The key did not previously exist in the dictionary,6// so the result is `nil`7//8let old = numbers.insert(key: "fortyTwo", 42)9
10// `old` is `nil`11// `numbers` is `{"twentyThree": 23, "fortyTwo": 42}````
• `cadence•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`.

This function mutates the dictionary.

```1// Declare a dictionary mapping strings to integers.2let numbers = {"fortyTwo": 42, "twentyThree": 23}3
4// Remove the key `"fortyTwo"` from the dictionary.5// The key exists in the dictionary,6// so the value associated with the key is returned.7//8let fortyTwo = numbers.remove(key: "fortyTwo")9
10// `fortyTwo` is `42`11// `numbers` is `{"twentyThree": 23}`12
13// Remove the key `"oneHundred"` from the dictionary.14// The key does not exist in the dictionary, so `nil` is returned.15//16let oneHundred = numbers.remove(key: "oneHundred")17
18// `oneHundred` is `nil`19// `numbers` is `{"twentyThree": 23}````
• `cadence•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.

```1// Declare a dictionary mapping strings to integers.2let numbers = {"fortyTwo": 42, "twentyThree": 23}3
4// Find the keys of the dictionary.5let keys = numbers.keys6
7// `keys` has type `[String]` and is `["fortyTwo","twentyThree"]````
• `cadence•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.

```1// Declare a dictionary mapping strings to integers.2let numbers = {"fortyTwo": 42, "twentyThree": 23}3
4// Find the values of the dictionary.5let values = numbers.values6
7// `values` has type [Int] and is `[42, 23]````
• `cadence•fun containsKey(key: K): Bool`

Returns true if the given key of type `K` is in the dictionary.

```1// Declare a dictionary mapping strings to integers.2let numbers = {"fortyTwo": 42, "twentyThree": 23}3
4// Check if the dictionary contains the key "twentyFive".5let containsKeyTwentyFive = numbers.containsKey("twentyFive")6// `containsKeyTwentyFive` is `false`7
8// Check if the dictionary contains the key "fortyTwo".9let containsKeyFortyTwo = numbers.containsKey("fortyTwo")10// `containsKeyFortyTwo` is `true`11
12// Invalid: Check if the dictionary contains the key 42.13// This results in a type error, as the key type of the dictionary is `String`.14//15let containsKey42 = numbers.containsKey(42)```

### Dictionary Keys

Dictionary keys must be hashable and equatable.

Most of the built-in types, like booleans and integers, are hashable and equatable, so can be used as keys in dictionaries.