Icon HelpCircleForumIcon Link

⌘K

Icon HelpCircleForumIcon Link

Icon LinkVectors

In Sway, a Vector is a dynamic-sized collection of elements of the same type. Vectors can hold arbitrary types, including non-primitive types.

Icon LinkWorking with Vectors in the SDK

A basic Vector in Sway is similar to a TypeScript Array:

// Sway Vec<u8>
const basicU8Vector = [1, 2, 3];

Consider the following example of a EmployeeData struct in Sway:

pub struct EmployeeData {
name: str[8],
age: u8,
salary: u64,
idHash: b256,
ratings: [u8; 3],
isActive: bool,
}

Now, let's look at the following contract method. It receives a Vector of the Transaction struct type as a parameter and returns the last Transaction entry from the Vector:

fn echo_last_employee_data(employee_data_vector: Vec<EmployeeData>) -> EmployeeData {
	employee_data_vector.get(employee_data_vector.len() - 1).unwrap()
}

The code snippet below demonstrates how to call this Sway contract method, which accepts a Vec<Transaction>:

// #import { getRandomB256 };
 
const employees = [
	{
	name: 'John Doe',
	age: 30,
	salary: 8000,
	idHash: getRandomB256(),
	ratings: [1, 2, 3],
	isActive: true,
	},
	{
	name: 'Everyman',
	age: 31,
	salary: 9000,
	idHash: getRandomB256(),
	ratings: [5, 6, 7],
	isActive: true,
	},
];
const { value } = await contract.functions
	.echo_last_employee_data(employees)
	.txParams({ gasLimit: 10_000 })
	.simulate();

Icon LinkReturning vectors

Currently, returning vectors is not supported by Sway. If you try returning a type that is or contains a Vector, you will get a compile-time error.