Like Rust, ifs are expressions in Sway. What this means is you can use if expressions on the right side of a let statement to assign the outcome to a variable.
Sway supports advanced pattern matching through exhaustive match expressions. Unlike an if statement, a match expression asserts at compile time that all possible patterns have been matched. If you don't handle all the patterns, you will get compiler error indicating that your match expression is non-exhaustive.
The basic syntax of a match statement is as follows:
let result =match expression { pattern1 => code_to_execute_if_expression_matches_pattern1, pattern2 => code_to_execute_if_expression_matches_pattern2, pattern3 | pattern4 => code_to_execute_if_expression_matches_pattern3_or_pattern4... _ => code_to_execute_if_expression_matches_no_pattern,}
Some examples of how you can use a match statement:
script;// helper functions for our examplefnon_even(num:u64) { // do something with even numbers}fnon_odd(num:u64) { // do something with odd numbers}fnmain(num:u64) -> u64 { // Match as an expressionlet is_even =match num %2 {0=>true, _ =>false, }; // Match as control flowlet x =12;match x {5=>on_odd(x), _ =>on_even(x), }; // Match an enumenumWeather {Sunny: (),Rainy: (),Cloudy: (),Snowy: (), }let current_weather =Weather::Sunny;let avg_temp =match current_weather {Weather::Sunny=>80,Weather::Rainy=>50,Weather::Cloudy=>60,Weather::Snowy=>20, };let is_sunny =match current_weather {Weather::Sunny=>true,Weather::Rainy|Weather::Cloudy|Weather::Snowy=>false, }; // match expression used for a returnlet outside_temp =Weather::Sunny;match outside_temp {Weather::Sunny=>80,Weather::Rainy=>50,Weather::Cloudy=>60,Weather::Snowy=>20, }}
Loops in Sway are currently limited to while loops. This is what they look like:
while counter <10 { counter = counter +1;}
You need the while keyword, some condition (value < 10 in this case) which will be evaluated each iteration, and a block of code inside the curly braces ({...}) to execute each iteration.