In Sway, you can use a variety of basic types to construct smart contracts.
u8: An 8-bit unsigned integer, with values ranging from 0 to 2^8-1.u16: A 16-bit unsigned integer, with values ranging from 0 to 2^16-1.u32: A 32-bit unsigned integer, with values ranging from 0 to 2^32-1.u64: A 64-bit unsigned integer, with values ranging from 0 to 2^64-1.str): This is a string of dynamic length.str[N]): This is a string of fixed length, where N is the length of the string.bool: A boolean type, which can be true or false.b256: This is a 256-bit number, equivalent to 32 bytes.
In the code provided, we define a smart contract named MyContract with a function called test_func that returns a boolean value. Inside this function, we demonstrate how to use these basic types.u8, u16, u32, and u64, all assigned the value 123.s_slice with the value "fuel".s_array of length 4, also with the value "fuel".boo with the value true.b_256 with a 32-byte hexadecimal value.The test_func function of this smart contract ultimately returns true. This simple example is intended to show you how to use these basic types in Sway. We hope this tutorial helps you better understand the basic types of Sway.
contract;
// Compound types
// - Tuples
// - destructuring
// - Structs
// - Arrays
struct Point {
x: u64,
y: u64,
}
abi MyContract {
fn test_func() -> Point;
}
impl MyContract for Contract {
fn test_func() -> Point {
// Tuples
let t: (u64, bool) = (42, true);
// Access tuple value
assert(t.0 == 42);
assert(t.1);
// Destructuring a tuple (type annotation is optional)
let (num, boo) = t;
// Tuple of length 1
let one: (u64, ) = (123, );
// Struct
let p = Point { x: 1, y: 2 };
// Access struct fields
assert(p.x == 1);
assert(p.y == 2);
// Array
let u_arr: [u8; 5] = [1, 2, 3, 4, 5];
let s_arr: [str; 4] = ["cat", "dog", "snake", "fish"];
let struct_arr: [Point; 2] = [Point { x: 1, y: 2 }, Point { x: 11, y: 22 }];
// Mutating array
let mut mut_arr: [bool; 2] = [true, false];
mut_arr[1] = true;
p
}
}