In Sway, a Vector is a dynamic-sized collection of elements of the same type. Vectors can hold arbitrary types, including non-primitive types.
A basic Vector in Sway is similar to a TypeScript Array:
// Sway Vec<u8>
const basicU8Vector = [ 1 , 2 , 3 ];
Icon ClipboardText
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 ,
}
Icon ClipboardText
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 ()
}
Icon ClipboardText
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). simulate ();
Icon ClipboardText
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.